1.Using a hash map to trade space for time
Storing what you have already seen in a hash map or set turns a repeated linear search into a single O(1) lookup — spending O(n) extra memory to cut an O(n²) scan down to O(n).
Key features
- This is the first question to ask when a brute force is O(n²): "can a hash map or set remember something to avoid the inner loop?"
- The trade is real, not free: it costs O(n) extra memory to buy back the time
- The pattern repeats everywhere: Two Sum, grouping anagrams, detecting duplicates, and counting frequencies are all this same trade applied to a different question
Before writing a nested loop, ask whether a hash map or set can remember what you have seen — that one question turns most O(n²) brute forces into O(n).