Counting: frequency as state you can update
Why a frequency map beats sorting for almost every "compare these multisets" question, when to count into an array instead, how a count becomes incremental state that composes with a sliding window, and the two O(n) tricks — bucket-by-count and the majority vote — that a heap-shaped answer misses.
What you'll be able to do
- Write the count-then-compare solution for a multiset question and state its bound against the sorting solution
- Decide between an array, a plain object, and a Map for a counter using the key domain
- Maintain a count incrementally inside a window instead of recomputing it per step
- Derive top-k by frequency in O(n) with bucketing, and say when a heap is the better answer anyway
- State the Boyer–Moore majority invariant and why a second pass is sometimes required
Before this: hash-maps, sliding-window
The rest of this lesson is in the app
Why a frequency map beats sorting for almost every "compare these multisets" question, when to count into an array instead, how a count becomes incremental state that composes with a sliding window, and the two O(n) tricks — bucket-by-count and the majority vote — that a heap-shaped answer misses. This walkthrough runs about 22 minutes, with runnable code you can edit and re-run as you read.
Continue in ChannelPulseThe first module of every track is free to read on the web — see what's open in Coding & data structures.