Two Sum: from brute force to a one-pass hash map
Company tags are compiled from public interview reports and are signals, not guarantees.
What interviewers are testing
Two Sum is the standard opening coding question because almost everyone can write the brute force, yet far fewer can derive the one-pass hash map and justify the switch. Interviewers watch how you reframe the problem from comparing pairs to querying for a complement, whether you keep the scan single-pass, and whether you can state the space-time trade-off without prompting. The follow-ups reveal whether you noticed the duplicate-value trap and can adapt the same idea to sorted input and to Three Sum.
Mental model
For each element the partner you need is fully determined: complement = target - nums[i]. Instead of scanning the rest of the array for that partner, remember every value already visited in a hash map keyed by value. If the complement is in the map, its index and the current index are the answer; otherwise store the current value and move on. One pass, average O(n) time, O(n) extra space.
Step-by-step solution
Step 1: Brute force checks every pair
Start with the honest solution so the improvement has something to beat. For each index i, scan every j greater than i and test whether nums[i] + nums[j] equals the target. The animation follows the loops on nums = [3, 2, 4, 3] with target 6: the first two probes miss, and the third finds 3 + 3. Every element is compared with every later element, so the work is (n-1) + (n-2) + ... + 1 = n(n-1)/2 comparisons, which is O(n²) time and O(1) extra space. On a ten-thousand-element array that is roughly fifty million additions, all to find a pair that a single organized pass could locate with ten thousand lookups. The brute force is the right baseline to say out loud: it proves you can solve the problem and isolates exactly what the faster solution must remove, namely the repeated rescanning.
Step 2: Ask for the complement
Brute force asks whether any other element pairs with this one, and answering costs a full rescan. Flip the question: if nums[i] must pair with an already-seen element, that partner's value is determined, complement = target - nums[i]. So before processing index i, the only question that matters is whether the complement has been seen. A hash map keyed by value answers that in one lookup. The animation shows the invariant taking shape: after processing each index, the map contains every value from indices before i. For [3, 2, 4, 3] and target 6, index 0 needs a 3 and finds nothing; index 1 needs a 4 and finds nothing; index 2 needs a 2 and finds it stored from index 1. That is the whole trick: the pair is discovered from the second element's point of view, so the array is walked exactly once.
Step 3: One pass with a hash map
The complete JavaScript solution is nine lines: create a Map, loop once, compute the complement, check membership, and insert on a miss. Order matters - check before insert. If you inserted first, nums[i] could match itself, and an input like [3, 3] with target 6 would be reported with the same index twice. Watch the animation walk [3, 2, 4, 3]: index 0 asks for 3, misses, and stores 3 -> 0; index 1 asks for 4, misses, and stores 2 -> 1; index 2 asks for 2, hits the stored index 1, and returns [1, 2] without ever looking at index 3. Notice that the hash-map answer differs from the brute-force answer [0, 3] - both are valid because the problem accepts any qualifying pair. This is the version interviewers want you to arrive at by derivation, not recollection.
javascriptfunction 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 []; }Step 4: Why O(1) lookup pays
A hash map is a time-for-space trade. The brute force spends O(1) memory and O(n²) time; the one-pass solution spends O(n) memory to buy O(1) average lookups. The map stores at most one entry per distinct value seen, so its footprint grows linearly with the input. Lookups are O(1) on average because a good hash function spreads keys across buckets; with many collisions, or a deliberately adversarial key set, operations can degrade toward O(n), which is why production hash maps randomize seeds to prevent hash-flooding attacks. Watch the animation: every insert lands in a bucket and every has/get probes that bucket instead of scanning the array. If memory were the tight constraint, sorting plus two pointers would give O(1) space at O(n log n) time. The trade is yours to defend, not a universal law.
Step 5: Duplicates and missing pairs
Duplicate values are where candidates slip. With nums = [3, 3] and target 6, the correct output is [0, 1]. Check-then-insert handles it naturally: index 0 stores 3 -> 0, and index 1 finds the complement 3 at index 0 before it ever considers overwriting the entry. If you inserted first, index 0 would find itself and report [1, 1]. The map keeps only one index per value, so with many duplicates you get the most recent compatible partner, which is fine because the problem asks for any valid pair. Also decide what a missing pair returns: the standard contract returns an empty array, but some variants throw or guarantee exactly one answer, so state your assumption. Finally, complement arithmetic is safe with negative values and zeros, but fixed-width languages must watch for overflow when target - nums[i] crosses the integer bounds.
Edge cases & traps
- Duplicate values such as [3, 3] with target 6: check the map before inserting, or index 0 finds itself and returns [1, 1] instead of [0, 1].
- No valid pair: the loop should exit and return an empty array, but some variants guarantee exactly one solution - state the contract before coding.
- Negative values and zeros are safe: complement = target - nums[i] needs no special casing; absolute-value heuristics break them.
- Integer overflow in fixed-width languages: target - nums[i] can cross the integer bounds even when the final answer is valid - use 64-bit arithmetic or reorder the comparison.
- Huge duplicate runs overwrite one map entry per value: since the check happens first, you still get the most recent compatible partner, which satisfies any-valid-pair contracts.