CodeArchon

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.

1class LRUCache:
2 def __init__(self, capacity):
3 self.cap = capacity
4 self.m = OrderedDict()
5 def get(self, key):
6 if key not in self.m: return -1
7 self.m.move_to_end(key)
8 return self.m[key]
9 def put(self, key, value):
10 if key in self.m: self.m.move_to_end(key)
11 self.m[key] = value
12 if len(self.m) > self.cap:
13 self.m.popitem(last=False)
Variables
size=0
capacity=2

How to think about it

  1. Doubly-linked list is required for O(1) node removal given a pointer.
  2. LinkedHashMap (Java) / OrderedDict (Python) encapsulate this pattern.
  3. 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 11
{"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