LRU cache
A fixed-capacity cache that evicts the least recently used entry when full. get and put in O(1) – a map plus a doubly linked list.
A user-profile service queries a slow database, so it keeps recently read profiles in memory. Memory is limited: when space runs out, the least recently used entry goes. Both operations must be constant time – the cache sits on the hot path of every request.
Task
A class LRUCache with capacity capacity ≥ 1:
| Operation | Behaviour |
|---|---|
get(key) | returns the value or -1 when the key is absent; a hit makes the entry the most recent |
put(key, value) | inserts or updates the entry and makes it the most recent; if inserting a new key pushes the size above the capacity, evicts the least recently used entry |
size | number of entries |
Names: JS/TS LRUCache, get, put, getter size; Python LRUCache, get, put, len(cache); C# LruCache, Get, Put, Count; Java LruCache, get, put, size(); Go NewLRUCache(capacity), Get, Put, Len.
Example
Capacity 2:
| Operation | Result | Contents (least → most recently used) |
|---|---|---|
put(1, 1), put(2, 2) | – | 1, 2 |
get(1) | 1 | 2, 1 |
put(3, 3) | – | 1, 3 (2 evicted) |
get(2) | -1 | 1, 3 |
put(1, 10) | – | 3, 1 |
put(4, 4) | – | 1, 4 (3 evicted) |
get(1) | 10 | 4, 1 |
Constraints
1 ≤ capacity ≤ 100,000, keys and values are integers0 … 10⁹.- Up to 200,000 operations per test.
Expected complexity
get and put in O(1) (average), O(capacity) memory.
Topics: Proxy