progress

~/problems / Linked lists / LRU / LFU cache

A recency list

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Every LRU cache sits on one structure: keys ordered by recency, where any key can jump to the front and the oldest can be dropped in O(1). Build just that.

Implement class RecencyList:

  • touch(key): make key the most recent (adding it if new).
  • pop_oldest(): remove and return the least recent key, or None.
  • __len__(): the number of keys.
  • keys(): all keys, most recent first (for the tests; O(n) is fine).
r = RecencyList()
r.touch("a"); r.touch("b"); r.touch("c")
r.keys()          # ["c", "b", "a"]
r.touch("a")      # "a" moves to the front
r.keys()          # ["a", "c", "b"]
r.pop_oldest()    # "b"
len(r)            # 2

Use a dict from key to node plus a doubly linked list with sentinel head and tail (dummy end nodes that hold no key, so every real node has neighbours on both sides; not OrderedDict). ⭐ Bonus: a speed test with 200,000 operations earns a star for O(1) touch and pop_oldest.

Show hint

store the key in each node so unlinking tail.prev tells you which dict entry to delete.

Topic: LRU / LFU cache. Hash map + doubly linked list for O(1) get/put.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc