I knew the hash map part immediately but fumbled explaining why the doubly linked list of frequency buckets actually gives you O(1).
Start by clarifying requirements: stream of keys, operations increment(key), decrement(key), and topK() returning K most frequent keys. Propose a hybrid data structure combining a hash map for O(1) frequency lookup and a doubly linked list of frequency buckets, where each bucket contains a set of keys with that frequency. For topK, maintain a separate min-heap of size K or a sorted list of buckets to retrieve top K efficiently.
Pro tip: Mention that the bucket list approach gives O(1) amortized updates because each increment/decrement moves a key at most one bucket, and topK can be O(K) by traversing from the highest frequency bucket. Also note that if K is small, a heap is simpler, but for large K the bucket list is better.
Ask about stream size, K value, whether decrement can make frequency negative, and if topK needs to be sorted. Confirm O(1) amortized for updates and discuss expected topK complexity.
Use a hash map from key to its frequency and a node in a doubly linked list of frequency buckets. Each bucket holds a set of keys with the same frequency. Maintain buckets in increasing order of frequency.
For increment: look up key, move it to the next higher frequency bucket (create if needed), update hash map. For decrement: move to previous bucket, remove key if frequency becomes zero. Both are O(1) amortized because each move is constant time.
Traverse buckets from highest frequency downward, collecting keys until K are gathered. If K is large, consider maintaining a min-heap of size K updated on each frequency change, but that adds O(log K) per update. Discuss trade-offs.
State that updates are O(1) amortized, topK is O(K) with bucket traversal. Handle edge cases: empty stream, K larger than distinct keys, decrement below zero, and concurrent access if needed.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.