Constant-Time Hot Key Counter With Max and Min Lookups
Last updated: November 29, 2026
Quick Overview
Design a counter for cache keys that supports inc(key), dec(key), get_max_key() and get_min_key(), all in O(1) time, removing a key when its count drops to zero.
Microsoft
November 29, 20260
0
0 solved
Design a counter for cache keys that supports inc(key), dec(key), get_max_key() and get_min_key(), all in O(1) time, removing a key when its count drops to zero.
A Microsoft onsite design-a-data-structure round in the style of Azure Cache and Bing serving teams, which track hot and cold keys to drive eviction and sharding. Interviewers use it to see whether a candidate can reason about linked bucket structures and keep invariants intact under every update.
What the Interviewer Expects
- Explain why a heap gives O(log n), not O(1)
- Use a doubly linked list of count buckets in increasing order
- Map each key to its bucket for O(1) moves
- Create neighbor buckets only when the adjacent count is missing
- Delete empty buckets immediately to keep max and min at the ends
Key Topics to Cover
How to Approach This
- Clarify input constraints and edge cases before writing code.
- Walk through your approach verbally and confirm with the interviewer before coding.
- Start with a brute force solution, then optimize. Mention time and space complexity.
- Test your solution with examples, including edge cases like empty input or duplicates.
- Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
- How would you support inc by an arbitrary amount?
- How would you make the counts decay over time so stale hot keys cool off?
- How would you approximate this for billions of keys with bounded memory?
Sharpen Your Skills on Codemia
Practice similar problems with our interactive workspace, get AI feedback, and track your progress.
Practice DSA ProblemsSample Answer
Requirements
inc(key) adds 1, inserting the key with count 1 if new. dec(key) subtracts 1 and removes the key at zero; decrementing a missing key is a no-op. get_max_key and get_min_key return any key with...
High-Level Design
Keep a doubly linked list of buckets ordered by count, each bucket holding the set of keys with exactly that count, between sentinel head and tail nodes. A dict maps each key to its bucket. Becaus...