Two sum (hash map)
Given an array of integers nums in no particular order and a target, return the positions of the two values that add up to it. Exactly one pair does, no value may be paired with itself, and it is the positions that come back rather than the values.
Examples
Example 1
- Input
- nums = [7, 1, 4, 9, 3]target = 10
- Output
- 1 + 9 = 10, and they sit at positions 1 and 3 with two other numbers between them.
[1,3]
Example 2
- Input
- nums = [7, 1, 4, 9, 3]target = 99
- Output
- No two of the same five numbers add to 99, so nothing comes back.
[]
The Code
function twoSum(nums, target) {
const seen = {};
for (let i = 0; i < nums.length; i++) {
const need = target - nums[i];
if (seen[need] !== undefined) return [seen[need], i];
seen[nums[i]] = i;
}
return [];
}
twoSum([7, 1, 4, 9, 3], 10);Explanation
Every value is remembered with its position, so a pair is found the moment its second half arrives rather than by trying every pair.
- 1
needistarget − nums[0], so 3.seenis empty, so there is nothing to pair with — andseen[7] = 0records this number against its position.i7011429334need=3seen={}
seen[7] = 0
- 2
needis 10 − 1 = 9, which is not inseeneither, soseen[1] = 1. This is the entry the answer comes out of.70i11429334need=9seen={7: 0}
seen[1] = 1
- 3
needis 10 − 4 = 6, a number this array never contains.seen[4] = 2.7011i429334need=6seen={7: 0, 1: 1}
seen[4] = 2
- 4
needis 10 − 9 = 1, andseen[1]is 1 — so the function returns those two positions, without ever reading the 3 at the end.701142i9334need=1seen={7: 0, 1: 1, 4: 2}
return [1, 3]
More like this
All arrays & loops examples (10) →- FizzBuzz The classic warm-up — Fizz, Buzz, or the number.
- Array maximum Track the largest seen so far in a single pass.
- Product except self Everything to the left of a position, times everything to its right.
- Majority element Pair off disagreeing votes; the majority always survives.
- Merge intervals Sort by start, then either extend the last interval or begin a new one.
- Top K frequent Bucket values by their count, then read the buckets from the top.