Given an array of integers nums and an integer target, return indices of the two numbers that add up to target. You may assume exactly one solution exists, and you may not use the same element twice.
nums = [2,7,11,15], target = 9[0,1]| Value (Key) | Index (Value) |
|---|
A HashMap gives O(1) average-case lookup. For every element we check whether its complement already exists — meaning we've previously seen the other number that would complete the sum. If found, we immediately have both indices. If not, we record the current number for future lookups. This single pass eliminates the need for a brute-force O(n²) nested loop.
Checking every pair works, but it is O(n²). For a big array, that is far too slow.
For each number, ask: have I already seen the number I need? The number you need is the target minus the current number. A hash map from value to index answers that in constant time.
Two Sum means storing what you have seen in a hash map. For each number, look up target minus the number.
Run the animation above on your own input, or watch the 1:12 video explanation of Two Sum with a dry run and Java code.