Hashing: Hash sets and frequency maps
Goal: Learn the pattern first, then apply it to the 6 roadmap problems in this chapter.
When this pattern appears
You need fast membership, counts, grouping, or a complement lookup.
The reusable idea
Choose a key that preserves exactly the information needed: a value, frequency vector, or prefix sum.
A deliberate problem-solving routine
- Write the input and output in plain language. Identify whether order, duplicates, or mutation matter.
- Work a tiny example by hand; label the state you wish you had at each step.
- Choose the structure or invariant that stores that state.
- Establish a brute-force baseline, then show exactly which repeated work the pattern removes.
- State the invariant before the loop, after each iteration, and at termination.
- Test smallest, boundary, duplicate, and adversarial cases.
Watch the animated pattern
The diagram above this lesson animates the core state changes for this chapter. Use pause and step to predict what moves next. The same invariant should explain each application, even when the problem story changes.
Questions to ask yourself
What fact about the past would make the current item useful? Store exactly that fact.
Common failure modes
Insert-versus-check order, duplicate values, key collisions from weak signatures, and negative prefix sums.
Chapter problems from the workbook
- #4 · Valid Anagram — Day 2, Easy. Open problem ↗
- #5 · Two Sum — Day 2, Easy. Open problem ↗
- #6 · Group Anagrams — Day 2, Medium. Open problem ↗
- #7 · Top K Frequent Elements — Day 3, Medium. Open problem ↗
- #8 · Longest Consecutive Sequence — Day 3, Medium. Open problem ↗
- #9 · Subarray Sum Equals K — Day 4, Medium. Open problem ↗
Interview explanation
A concise explanation has four parts: the key observation, the maintained invariant, why each step preserves it, and the time/space complexity. Avoid naming a pattern as a substitute for proving the step is safe.