Two Sum
Given an array of integers numskk
Example 1
Output: [1, 2]
Explanation: after adding up values at index 1 and 2 , that adds up to the target 6.
Example 2
Output: [0,1]
Explanation: after adding up values at index 0 and 1 , that adds up to the target 6.
Constraints:
-
2 <= nums.length <= 104 -
-109 <= nums[i] <= 109 -
-109 <= target <= 109
Contents
Solution 1 - Using HashMap
The main intution behind this solution is, as per the problem statement x + y = kk(x, y)xk-xnumsx = nums[i]k-xHashMap
Implementation steps:
-
We will first create a
, to store elements of input arrayHashMap and their indexes, call itnums .map -
Then, loop through every element of
, and check ifnums containsmap or not, if it contains, that means we have found the pair, so return their indexes as an array. If we dont find it, then add current element and it's index to theK- nums[i] .map
public int[] twoSum(int[] array, int target) {
// base case to find a pair we need atleast two elements.
if(array == null || array.length < 2) {
throw new IllegalArgumentException("input array should contain atleast two elements");
}
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<array.length; i++) {
int current = array[i];
int diff = target - current;
Integer pairIndex = map.get(diff);
if(pairIndex != null) { // we found other number index which adds up to target k
return new int[] {pairIndex, i};
} else {
map.put(current, i); // store the number and its index
}
}
return null; // none found
}
Complexity Analysis:
Above code runs in O(n) time complexity where n
Space complexity is O(n) as we are storing elements into HashMap.
illustration:
Consider below example
Step 1 We initialize an intermediate data structure HashMap to store element and it's index.
Step 2 Loop through elements and find if the other pair element visited or not.
- In 1st iteration, take the diff between target and first element
, is 16 already present in HashMap ? HashMap is empty, so store current number 2 and its index 0 into map and continue with next element.18 - 2 = 16 - In 2nd iteration, take the diff between target and second element
, is 11 already present in HashMap ? No, so store current number 7 and its index 1 into map and continue with next element.18 - 7 = 11 - In 3rd iteration, take the diff between target and third element
, is 7 already present in HashMap ? Yes, we found our answer. We now have have the indices of current element and element 7 from map {1, 2}.18 - 11 = 7
| Number | Index |
|---|---|
| 2 | 0 |
| Number | Index |
|---|---|
| 2 | 0 |
| 7 | 1 |
Above implementations source code can be found at