~/problems
Problems
Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.
LRU / LFU cache
Hash map + doubly linked list for O(1) get/put.
Notes
Recognise it when: "O(1) get/put with eviction", caching, most-recently-used ordering.
A dict maps keys to nodes, plus a doubly linked list with sentinel head and tail: head.next is the most recent, tail.prev the least recent.
get: unlink the node, push it to the front.put: update and move it, or insert at the front; if over capacity, unlinktail.prevand delete its key from the dict.
Gotchas
- Store the key in the node so eviction can delete it from the dict.
- Updating an existing key refreshes its recency.
OrderedDict.move_to_end/popitem(last=False)is fine in real code, but interviewers usually want the list.- LFU: a dict of frequency -> OrderedDict, plus a
min_freqtracker.
6 problems
Interview roadmap
Linked lists Reverse, merge, detect cycles, build an LRU cache.
LRU / LFU cache guide
- Basics: a recency list (dict + doubly linked list) basics py · c++ · java easy
- Recent files menu py · c++ · java easy
- LRU Cache py · c++ · java medium
- LFU Cache py · c++ · java hard
- LRU, LFU, then a pluggable eviction policy 3 levels Citadel hard
- OA: LRU cache with TTL and weighted size 3 levels Snapchat hard