Spot the bug: get forgets the order
Standard · Find the bug · about 8 min
This LRU cache runs get K and put K V commands and returns the get results. The map keeps keys in insertion order, so its first key is the least recently used. It gives wrong answers for some inputs. Click the line with the bug, then fix it.
Example 1
Input:
[2,["put 1 1","put 2 2","get 1","put 3 3","get 1"]]
Output:
[1,1]
The buggy code returns [1, -1]: it evicts 1 although 1 was just read.
Constraints
- 1 ≤ capacity ≤ 3,000
- 0 ≤ commands.length ≤ 10,000
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
- LFU cache Challenge