Two Sum
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target . You may assume each input has exactly one solution, and you may not use the same element twice. Use a hash map that remembers every value you have already seen and its index, so for each new number you can instantly check whether its matching partner showed up earlier.
Constraints
- 2 ≤ nums.length ≤ 104
- -109 ≤ numsi ≤ 109
- -109 ≤ target ≤ 109
- Only one valid answer exists
Example
nums = [2, 7, 11, 15], target = 9[0, 1]Explanation nums0 + nums1 = 2 + 7 = 9, so the answer is the indices [0, 1].
In plain terms
- Hash map
- A lookup table that stores key-value pairs and lets you check "have I seen this before?" in roughly constant time, instead of scanning a list.
Remember each value seen so far in a hash map
i=0 (value 2). complement = 9 - 2 = 7, not yet in the map. Store 2 -> 0.
What happens in this step
i = 0 (value 2) complement = target - nums[i] = 9 - 2 = 7 map has no entry for 7 Store nums[0]=2 at index 0 in the map.
Steps to visualize
- Walk the array from left to right, one number at a time.
- At each number, compute the complement: target minus the current number.
- Check the hash map for that complement — if it is there, you found the pair.
- Otherwise, store the current number and its index in the hash map and keep going.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
i=0 (value 2). complement = 9 - 2 = 7, not yet in the map. Store 2 -> 0.
What happens in this step
i = 0 (value 2) complement = target - nums[i] = 9 - 2 = 7 map has no entry for 7 Store nums[0]=2 at index 0 in the map.
Solution
function twoSum(nums, target) {
const seen = new Map();
for (let i = 0; i < nums.length; i++) {
const complement = target - nums[i];
if (seen.has(complement)) {
return [seen.get(complement), i];
}
seen.set(nums[i], i);
}
return [];
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
nums = [2, 7, 11, 15], target = 9 | [0, 1] | example from the docstring |
nums = [3, 2, 4], target = 6 | [1, 2] | matching pair is not the first two elements |
nums = [3, 3], target = 6 | [0, 1] | the two matching numbers are equal values |
nums = [1, 2], target = 3 | [0, 1] | smallest valid input, exactly two elements |
nums = [-3, 4, 3, 90], target = 0 | [0, 2] | negative and positive numbers summing to zero |
nums = [1, 5, 9, 11], target = 20 | [2, 3] | matching pair is the last two elements |