Stacks & queuesAnimated
LRU Cache
A hash map plus a recency list evicts the least recently used item.
Time
O(1) get and put
Extra space
O(capacity)
Use it for
Caches in browsers, databases and operating systems.
How it works
- A cache has limited room. When it is full, the least recently used item is thrown out.
- Keep items ordered from least to most recently used (a hash map plus a linked list makes every step O(1)).
- A hit moves the key to the most-recent end. A miss adds it there and, if over capacity, evicts the key at the least-recent end.
- Frequently used items stay; forgotten ones fall off.
Watch it run
Loading animation…