Two Sum: the partner you've already seen
Find the two indices whose values add to a target. The brute-force answer is obvious and O(n²); the famous one trades a little memory for a single pass and O(n). The whole leap is one reframe — stop hunting for pairs, start remembering what you've passed.
Try every pair
Two nested loops: fix a number, test it against every later number, stop when a pair hits the target. It always works — and on a long array, it's slow. Watch where the effort goes.
9.For each of n numbers we may scan the whole rest of the array — about n²/2 comparisons. The deeper waste: every inner loop is just searching for one specific value, from scratch, over and over.
Every number has one partner
The fix isn't a faster search — it's not searching at all. The partner a number needs is completely determined, so the only real question is whether we've met it yet.
nums[1] = 7. How many other numbers could possibly complete it?x, its partner must be target − x — there is no other option. So replace "search the array for it" with "have I already seen it?", and make that question instant.Remember as you go, in a hash map
Walk the array once. At each number, ask the map for its complement; if it's there, you're done; if not, drop the current number into the map and keep walking. Every lookup and insert is O(1).
target − nums[i]. A hit gives me both indices immediately; a miss just files the current number for someone later. One pass, because the answer is always behind me."n² versus n
Same problem, two costs. Brute force re-searches; the hash map remembers. On a 10,000-element array that's the difference between ~50 million comparisons and ~10,000.
target − x, fully determined — so I don't search, I remember. One pass with a value→index map: look up the complement, return on a hit, otherwise store and continue. O(n) time for O(n) space."