DEV Community

akhilmdev
akhilmdev

Posted on

1 1

Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

  • You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Analysis

So, we need to have 2 numbers for the array so that the sum of those equal to targeted sum. feel's simple :-)...
But, Not sorted

First think that comes to mind is to take each element and find the target complement of element form remaining elements.

So this will take O(n^2) and space complicity of O(1)

Can we have better time complicity ?

Ya!! we do have!

We can keep a hash that holds target complement(target - currentValue) as key and index as value and if we find element in hash map then return the current index and index from hash map.

Lets code that!

var twoSum = function (nums, target) {
    result = [];
    const index_map = new Map();
    // Loop for each element in the array
    for (let i = 0; i < nums.length; i++) {
        let difference = target - nums[i];
        if (index_map.has(difference)) {
            result.push(i);
            result.push(index_map.get(difference));
            break;
        } else {
            index_map.set(nums[i], i);
        }
    }
    return result;
};
Enter fullscreen mode Exit fullscreen mode

So, Here the time complicity is O(n) and space complicity of O(n).

Conclusion

The best time complicity algorithm is to use the hash map, but that could take O(n) space complicity.

Always think of which is the requirement is it time or space and come up with the algorithm.

Thanks feel free to contact and keep learning!

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay