mediumLinked ListAmazonMicrosoftFacebookGoogle
LRU Cabinet Keeper
A librarian keeps the N most recently used books on a priority shelf; the least-recent one is evicted when the shelf is full.
Design a data structure that follows the Least Recently Used (LRU) cache constraints. Implement get(key) and put(key, value) in O(1).
Choose approach
1/10
Narrationstep 1 of 10
Empty cache, capacity = 2.
Variables
size=0
capacity=2
How to think about it
- Doubly-linked list is required for O(1) node removal given a pointer.
- LinkedHashMap (Java) / OrderedDict (Python) encapsulate this pattern.
- Promotion to head on get() is what makes it 'least recently used'.
Edge cases to catch in interview
- capacity = 1 → every put evicts previous.
- get on absent key returns -1 without touching order.
Examples
Example 1
1{"capacity":2,"ops":[["put",1,1],["put",2,2],["get",1]]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed