Given an array of integers
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
Implementation steps:
-
We will first create a
HashMap , to store elements of input arraynums and their indexes, call itmap . -
Then, loop through every element of
nums , and check ifmap containsK- nums[i] 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 themap .
Complexity Analysis:
Above code runs in O(n) time complexity where
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
18 - 2 = 16 , 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. - In 2nd iteration, take the diff between target and second element
18 - 7 = 11 , is 11 already present in HashMap ? No, so store current number 7 and its index 1 into map and continue with next element. - In 3rd iteration, take the diff between target and third element
18 - 11 = 7 , 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}.
Number | Index |
---|---|
2 | 0 |
Number | Index |
---|---|
2 | 0 |
7 | 1 |
Above implementations source code can be found at