LFU Cache
Problem
Design a fixed-capacity cache that evicts the entry with the lowest use count; when several entries tie on use count, evict the one among them that was used least recently. Implement LFUCache with:
__init__(capacity).get(key): return the value or-1if absent. A hit increments the key's use count.put(key, value): insert or update. Updating an existing key increments its use count; inserting a new key gives it a count of 1, evicting first if the cache is full.
Both operations must be O(1) average time.
0 <= capacity, up to a few thousand (a capacity of 0 means everyputis a no-op and everygetreturns-1).- Keys and values are non-negative integers.
- Expect up to a couple hundred thousand operations.
Examples
- Capacity 2:
put(10,1),put(20,2),get(10)→1(key 10 now has count 2);put(30,3)evicts key 20 (count 1, the minimum);get(20)→-1;get(30)→3(count 2);put(40,4): keys 10 and 30 both have count 2, key 10 was used less recently, so key 10 is evicted;get(10)→-1,get(30)→3,get(40)→4. - Capacity 1:
put(5,1),put(6,2)evicts key 5;get(5)→-1,get(6)→2. - Capacity 0:
put(9,1),get(9)→-1.
Hints
- Tracking counts in a hash map is easy; the hard part is finding the minimum-count key, and among those the least recent, in O(1).
- Group keys by use count. Within a group, what structure gives you least-recent removal and O(1) move-to-front? You already know it from LRU.
- Keep a map from count to a doubly linked list of nodes (LRU-ordered), a map from key to node, and a
min_countinteger. When a key is used, move it from listcto listc+1;min_countonly ever needs to change by resetting to 1 on insert or incrementing by one when listmin_countbecomes empty.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.