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
Coding & Algorithms
Software Engineer
Microsoft
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

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
doubly linked list
hash map
data structure design
O(1) operations
LFU
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. 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 Problems
Sample 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...


Submit Your Answer
Markdown supported