progress

~/problems / Linked lists / LRU / LFU cache

Recent files menu

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

easy ~15 min

An editor's Open Recent menu keeps at most capacity paths, most recent first. Build class RecentFiles(capacity):

  • open(path) -> str | None: move path to the top (adding it if new). If that makes more than capacity, drop and return the least recently opened; else return None.
  • forget(path) -> bool: remove path; return whether it was listed.
  • menu() -> list[str]: all paths, most recent first (O(n) is fine).
r = RecentFiles(3)
r.open("a.txt"); r.open("b.txt"); r.open("c.txt")   # all return None
r.open("a.txt")      # None: already listed, just moves to the top
r.menu()             # ["a.txt", "c.txt", "b.txt"]
r.open("d.txt")      # "b.txt" is dropped and returned
r.forget("c.txt")    # True
r.forget("c.txt")    # False
r.menu()             # ["d.txt", "a.txt"]

Build it from a dict plus a doubly linked list with sentinels, as in Basics: a recency list, not OrderedDict. Sentinels are dummy head and tail nodes that hold no path, so you never special-case an empty list. ⭐ Bonus: a speed test (200,000 calls) earns a star for O(1) open and forget.

Show hint

forget finds the node in the dict, joins its prev and next, and deletes the entry.

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