LRU Cache
Design a data structure for a Least Recently Used (LRU) cache with a fixed capacity. get(key) returns the value if present (and marks it most recently used) or -1 otherwise. put(key, value) inserts or updates the key; if this exceeds capacity, evict the least recently used key. Both operations must run in O(1) average time.
Open official problem prompt ↗Support constant-time get and put while always evicting the item that has gone longest without use.
A stack of papers on a desk: whenever you use one you move it to the top; when the desk overflows you toss the bottom paper, which is the one you touched least recently.
- Input
- LRUCache(2); put(1,1); put(2,2); get(1); put(3,3); get(2); put(4,4); get(1); get(3); get(4)
- Output
- [1, -1, -1, 3, 4]
- Why
- put(3,3) evicts key 2 (least recently used), and put(4,4) evicts key 1, so get(2) and get(1) return -1.
1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^5At most 2 * 10^5 calls to get and put