Two Sum


Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


Solution:

Since for each element 'x' present in the array, we will have to check whether a number 'y' exists in the array such that sum of two numbers is target and return indices of the number. 

We can also say that, for any element 'x' present in the array , find a number 'target-x' which is also present in the array.

One approach to the problem is to scan the complete array for finding number 'target-x' for each element 'x'. 

Another approach is to use dictionaries. For each element 'x' in the array, check whether the dictionary contains element 'target-x'.

So here, first we will scan the complete array to store the elements of the array in the dictionary with element as the key and index of the element as the value.


Time Complexity: O(n)

We are checking for map[nums[i]]>=2 to avoid fetching the same element twice.

For Example: 

Given nums = [2, 7, 11, 15], target = 4,

If we are trying to find complement of 2 which is 2 for target 4 then dictionary will still return true since the element is present but it's not an actual solution to the problem.


Comments

Popular posts from this blog

Longest Common Prefix

Roman To Integer