Two Sum
One pass with a dictionary. For each value, ask whether its complement target - value has already been seen; if it has, you have the pair. O(n) time and O(n) space, against O(n²) for the nested loops everyone writes first.
Overview
Turning a search into a lookup
The nested-loop version asks "does any later element pair with this one?", which is n²/2 comparisons. The insight is to invert it: you know exactly which number you need, so the question becomes "have I already seen target - value?" — and that is a dictionary lookup, not a search.
This is the same move as grouping anagrams by a key. Whenever a problem asks you to find a pair with a known relationship, look for the version where one member is computed rather than searched for.
Step through it
What to watch
- The dictionary only holds values already passed.
- Storing after the check is what stops an element pairing with itself.
- The answer is found without ever comparing two elements directly.
Say this out loud
"One pass with a dict of value to index. For each number I look up target minus it - if it's there, that's the pair. O(n) time, O(n) space. If the array were sorted I'd use two pointers instead and drop the space to O(1)."