This one took me a while to even understand what they were asking.
Start by clarifying requirements and constraints, then propose a design using a hash map for O(1) access to item nodes and a doubly linked list of frequency buckets to maintain order. Explain how updates adjust frequencies and move nodes between buckets, and how top K retrieval traverses buckets from highest frequency, using a recency list within each bucket for tie-breaking.
Pro tip: Mention that this is essentially an LFU cache with recency tie-breaking, and that the same design can be adapted for real-time trending items at Uber by adding time-decay or sliding windows.
Ask about expected data size, update patterns, and whether K is fixed or variable. Confirm that ties are broken by most recent update and that deletion occurs at zero frequency.
Use a hash map from item to node for O(1) access, and a doubly linked list of frequency buckets (each bucket contains a set of items with that frequency). Within each bucket, maintain a doubly linked list ordered by recency for tie-breaking.
For increment: move item to next higher frequency bucket (create if needed), updating recency. For decrement: move to lower bucket, and if frequency becomes zero, remove item. Ensure O(1) amortized by adjusting bucket pointers.
Traverse frequency buckets from highest to lowest, collecting items from each bucket's recency list until K items are gathered. This yields O(k) time if buckets are traversed efficiently, skipping empty buckets.
Compare with alternative designs like heaps or balanced trees, highlighting why this achieves O(1) updates and O(k) retrieval. Mention potential memory overhead and how to handle concurrent updates if needed.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.