LFU cache, then distribute it
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Amazon's coding round, last asked Nov 2025. It tests caching, data structures and distributed systems.
Implement a cache with a least-frequently-used eviction policy, then extend the idea to a stream of keys too large for one machine.
Part 1: LFUCache
Unless you agree on a different interface with the interviewer, assume:
-
LFUCache(capacity: int)—capacity >= 0. -
get(key: int) -> int— the value, or -1 if absent. A hit counts as a use. -
put(key: int, value: int) -> None— inserts or updates; an update counts as a use. When inserting a new key into a full cache, first evict the key used the fewest times; among ties, the one used least recently.
Both operations in O(1).
c = LFUCache(2)
c.put(1, 1); c.put(2, 2)
c.get(1) -> 1 # key 1 used twice, key 2 once
c.put(3, 3) # evicts 2
c.get(2) -> -1
c.get(3) -> 3 # keys 1 and 3 both used twice; 1 less recently
c.put(4, 4) # evicts 1
c.get(1) -> -1
c.get(3) -> 3
c.get(4) -> 4
LFUCache(0): every put is ignored and every get returns -1.
Part 2: distributed and streaming
Keys (user ids, item ids, search queries) now arrive as a high-volume stream spread over many machines, too many to count exactly on one node. Design a way to answer "what are the k most frequent keys right now?", over all time or over a recent window, with good accuracy.
Clarifying questions
- Does
puton an existing key count as a use? (Yes.) - What happens with capacity 0?
- In Part 2, how accurate must the top
kbe, and how fresh?
What a strong answer covers
- Part 1: a map from key to (value, count), a map from count to a doubly linked list (or ordered dict) of keys in recency order, and the current minimum count, which resets to 1 on every insert and rises by one when its list empties.
- Part 2: per-machine bounded summaries (Space-Saving or Misra-Gries for heavy hitters, a Count-Min sketch with a small heap), partitioned by key or merged periodically, since these summaries merge cleanly.
- Windows and decay: time-bucketed summaries that roll off, or exponentially decayed counts.
- Late and out-of-order events: event-time buckets with a grace period.
- The trade-offs between accuracy, memory and latency named and chosen, with the error bounds of the summary.
Follow-ups
- Make the cache safe for concurrent use.
- Shard the cache across machines with consistent hashing. What happens to frequencies when a node joins or leaves?
- Recent use should matter more than old use. Adapt the eviction rule.
Where it's asked
- Amazon · Coding · Last asked Nov 202555 min · Usually two rounds; one is often an object-oriented design built in steps · No AI
What it tests
caching · data structures · distributed systems
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
