progress

~/problems / Linked lists / LRU / LFU cache

LRU cache with TTL and weighted size

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

hard assessment 3 levels ~60 min Snapchat

Level 1 Plain LRU

Build Cache(capacity), where capacity >= 1:

  • get(key) returns the stored value, or None on a miss. A hit makes the key the most recently used.
  • put(key, value) inserts or overwrites the key and makes it the most recently used. If the cache now holds more than capacity keys, it drops the least recently used one.

⭐ Bonus: a speed test earns a star if both are O(1). OrderedDict is allowed, but writing the structure yourself is better interview practice. Keys are hashable and values are anything except None.

c = Cache(2)
c.put("a", 1); c.put("b", 2)
c.get("a")        # 1  ("b" is now least recent)
c.put("c", 3)     # drops "b"
c.get("b")        # None

Level 2 unlocks when level 1 passes.

Level 3 unlocks when level 2 passes.

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