CodingMedium
LRU Cache
Design a cache that holds at most capacity keys and drops the least recently used one when it runs out of room.
get(key) returns the value, or -1 when the key isn’t there. put(key, value) inserts or updates a key. Reading or writing a key makes it the most recently used. Both run in O(1) time.
Example 1
Input
capacity = 2
put(1, 1) · put(2, 2) · get(1) · put(3, 3) · get(2)Output1, -1get(1) makes key 1 the most recent, so put(3, 3) evicts key 2.
Constraints
- 1 ≤ capacity ≤ 3000
- 0 ≤ key, value ≤ 10⁴
- At most 2 · 10⁵ calls to get and put