Coding · must-tier · asked at Amazon, Apple, Google, Meta, Microsoft, Netflix
LRU Cache
Problem
Design a fixed-capacity cache that evicts the least recently used entry when full. Implement a class LRUCache with:
__init__(capacity): create a cache that can hold at mostcapacitykey/value pairs.get(key): return the value forkeyif present, otherwise-1. A successfulgetcounts as a use.put(key, value): insert or overwrite the value forkey. This counts as a use. If inserting a new key exceeds the capacity, evict the entry that was used least recently before inserting.
Both operations must run in O(1) average time.
- Capacity is at most a few thousand entries.
- Keys and values are non-negative integers.
- Expect up to a couple hundred thousand combined calls to
getandput.
Examples
- Capacity 2:
put(10,100),put(20,200),get(10)→100;put(30,300)evicts key 20 (key 10 was used more recently);get(20)→-1;put(40,400)evicts key 10;get(10)→-1,get(30)→300,get(40)→400. - Capacity 1:
put(5,50),put(6,60)evicts key 5;get(5)→-1,get(6)→60. - Capacity 2:
put(7,70),put(7,700)overwrites without eviction;get(7)→700. Overwriting an existing key never triggers eviction.
Hints
- A hash map gives O(1) lookup, but how do you know which key was used least recently without scanning?
- You need an ordering by recency that supports "move this element to the front" and "remove the last element" in O(1). Which linked structure does that?
- Hash map from key to node, plus a doubly linked list ordered by recency with sentinel head and tail.
getandputunlink the node and re-insert it at the front; eviction removes the node before the tail.
Last reviewed 8 September 2026
Locked
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.
Secure payment by Stripe · instant access · refund questions: [email protected]
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.