LFU Cache
Design an LFU (Least Frequently Used) cache with a given capacity. get(key) returns the value or -1 and counts as a use. put(key, value) inserts or updates; if the cache is full, evict the least frequently used key, breaking ties by evicting the least recently used among those. Both operations must run in O(1) average time. A get or put on a key increases its use frequency by one.
Open official problem prompt ↗Serve a fixed-capacity cache that evicts the least-used key, using recency only to break frequency ties, all in constant time.
Like a library that shelves books by how often they are borrowed; when space runs out it discards from the least-borrowed shelf, and among equally unpopular books, the one untouched longest.
- Input
- LFUCache(2); put(1,1); put(2,2); get(1); put(3,3); get(2); get(3); put(4,4); get(1); get(3); get(4)
- Output
- [null, null, null, 1, null, -1, 3, null, -1, 3, 4]
- Why
- put(3,3) evicts key 2 (freq 1 vs key1's freq 2); put(4,4) evicts key 1 (keys 1 and 3 both freq 2, key 1 least recently used).
0 <= capacity <= 10^40 <= key <= 10^50 <= value <= 10^9At most 2 * 10^5 calls to get and putget and put must be O(1) average time