LFU cache
Challenge · Write code · about 30 min
Simulate an LFU (least frequently used) cache that holds up to capacity keys and starts empty. Each cached key counts its uses. A get hit or a put adds one use, and a new key starts with 1 use. Run the commands in order:
get Kreturns the value of K, or-1if K is not cached.put K Vstores V under K. If K is new and the cache is full, first evict the key with the fewest uses. On a tie, evict the least recently used of those keys.
Return the results of the get commands in order. Each command must take O(1) on average.
Example 1
Input:
[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:
[1,-1,3,-1,3,4]
put 3 evicts 2, which has 1 use. put 4 finds 1 and 3 tied at 2 uses and evicts 1, the least recent.
Example 2
Input:
[2,["put 1 1","put 1 2","put 2 2","put 3 3","get 1","get 2","get 3"]]
Output:
[2,-1,3]
Updating key 1 gave it 2 uses, so 2 is evicted.
Constraints
- 1 ≤ capacity ≤ 3,000
- 0 ≤ commands.length ≤ 10,000
- 0 ≤ K ≤ 10,000 and 0 ≤ V ≤ 100,000
- Each command is
get Korput K V
Learn the idea first: LRU and LFU caches, a visual lesson.
More LRU and LFU caches problems
- Choose the structures Warm-up
- Count cache misses Warm-up
- Predict evictions Standard
- LRU cache Standard
- Spot the bug: get forgets the order Standard