2Sum
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.
Example 1:
Approach1: Dictionnary or Map
The general key to this problem is to be aware that there will always be one pair of numbers that will satisfy the target
value. If we assume that the list contains element (x1, x2, x3, xn)
, there will inevitably be a pair that exists such that xa + xb = target.
We first create a Dictionnary
d
that will map all elements of the list to their respective index.We then notice that we're able to solve the problem in one pass as we change the equation above to
xa = target - xb
. Since we already know thetarget
, as long as we maintain all previous numbers to our records as we iterate, we will be able to verify whetherxa = target - xb
orxb = target - xa
. Either way, we will find a corresponding pair.We iterate over the elements of list
num
, we verify whehther the dictionnary contains the complement pair. If it does not contain it, we add the element as well as it's index to the dictionary otherwise if it does, we have found a pair of element which equals thetarget
.
Time: O(n) Space: O(n)
Approach: Java Version
Last updated
Was this helpful?