Skip to content
StackDecode
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

  1. A cache has limited room. When it is full, the least recently used item is thrown out.
  2. Keep items ordered from least to most recently used (a hash map plus a linked list makes every step O(1)).
  3. 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.
  4. Frequently used items stay; forgotten ones fall off.

Watch it run

Loading animation…