Seen-set
O(n)Keep a set of everything so far. Each new item is one lookup: in the set, or not.
Reach for it when you need to know whether a value has turned up before, or whether one exists at all.Go deeper: How a hash map finds a keyMost brute-force answers compare every item with every other item. A hash map remembers what you have already seen, so one pass is enough.
Keep a set of everything so far. Each new item is one lookup: in the set, or not.
Reach for it when you need to know whether a value has turned up before, or whether one exists at all.Go deeper: How a hash map finds a keyFor each item, work out the partner that would complete it, and look that partner up. Store the item only afterwards.
Reach for it when two items have to combine into a target, and you need their positions.Go deeper: Counting, grouping and seen-before: three hash map patternsOne pass to count how many of each value there are. Every later question reads the counts, not the array.
Reach for it when the answer depends on how often things appear: anagrams, majorities, the top k.Go deeper: Counting, grouping and seen-before: three hash map patternsTurn each item into a key that equal items share, such as its sorted letters. Items with the same key go in the same list.
Reach for it when you need to sort things into buckets by some property they have in common.Go deeper: Counting, grouping and seen-before: three hash map patternsKeep a running total. The sum of any slice is the difference between two totals, so a map of totals seen finds slices with a given sum.
Reach for it when the question is about contiguous slices and their sums or products.Go deeper: Prefix sums: any range total in one subtractionWhen values are known to lie between 1 and n, the array itself can be the hash table. Mark value v at index v − 1.
Reach for it when values fit the array’s own index range and you are asked for constant extra space.Go deeper: Why reading an array by index is instantOnly one to learn by heart: the complement lookup from Two Sum. Look up what you need before you store what you have. Most of the others are a count or a set built the same way.
| # | Problem | Pattern | Difficulty | Solution |
|---|---|---|---|---|
| 1 | Contains Duplicate | Seen-set | Easy | Read |
| 2 | Valid Anagram | Frequency count | Easy | Read |
| 3 | Two Sum | Complement map | Easy | Read |
| 4 | Majority Element | Frequency count | Easy | Read |
| 5 | Group Anagrams | Group by key | Medium | Read |
| 6 | Top K Frequent Elements | Frequency count | Medium | Read |
| 7 | Product of Array Except Self | Prefix sums | Medium | Read |
| 8 | Valid Sudoku | Seen-set | Medium | Read |
| 9 | Longest Consecutive Sequence | Seen-set | Medium | Read |
| 10 | Subarray Sum Equals K | Prefix sums | Medium | Read |
| 11 | Find All Duplicates in an Array | Index as key | Medium | Read |
| 12 | First Missing Positive | Index as key | Hard | Read |