How Two Sum works
Walk the array once. For each value, compute complement = target − nums[i]. If the complement is already in the map, its stored index and i are the answer. Otherwise store nums[i] → i and move on. Checking before storing is what stops an element from pairing with itself.
The Python example looks for 18 in [2, 7, 11, 15, 3]. At index 2 the complement of 11 is 7, which was stored at index 1, so the answer is (1, 2).
What to watch for when it runs
- The map is drawn as a table that gains one row per step.
- The complement lookup is a single step each time — there is no inner loop.
- The run stops as soon as the pair is found, without reaching the rest of the array.
Time and space complexity
- Time
- O(n)
- Space
- O(n)
Hash lookups are O(1) on average. The brute-force double loop needs no extra memory but is O(n²).