LRU Cache
Asked of: Software Engineer
Last updated

What's being tested
This tests the LRU cache pattern: combining a hash map with a doubly linked list to support get and put in O(1) time. You must preserve both key-value lookup and recency ordering while correctly handling updates, eviction, capacity limits, and empty states.
Patterns & templates
-
Hash map + doubly linked list — map keys to nodes; list order is least-recently-used to most-recently-used.
-
Use sentinel
headandtailnodes to eliminate boundary branches when removing or inserting list nodes. -
get(key)returns-1or the agreed absence value; on a hit, detach the node and move it to the MRU end. -
put(key, value)updates existing nodes without increasing size; otherwise insert at MRU, then evict the LRU node if over capacity. -
Factor helpers such as
remove(node)andinsert_at_front(node); each performs constant pointer updates and keeps invariants centralized. -
Target
O(1)average time for both operations andO(capacity)space; never scan the list to find keys. -
Clarify capacity
0, repeated keys, repeated reads, missing keys, and whether values may benullor mutable objects.
Common pitfalls
Pitfall: Updating a key without moving it to MRU makes eviction order incorrect; every successful access must refresh recency.
Pitfall: Removing the LRU node from the list but not the map leaves stale entries and breaks size accounting.
Pitfall: Claiming
O(1)while using an array, singly linked list, or linear search for eviction violates the required complexity.
Practice these
The practice cards below cover the canonical variants — solve all of them and time yourself.
Featured in interview prep guides
Practice questions
- Implement Sliding Windows and LRU CacheByteDance · Software Engineer · Onsite · medium
- Implement Expiring LRU CacheByteDance · Software Engineer · Technical Screen · hard
- Add TTL to an LRU cacheByteDance · Software Engineer · Onsite · hard
- Implement an LRU cacheAffirm · Software Engineer · Onsite · easy
Related concepts
- LRU Cache Design And PersistenceCoding & Algorithms
- LRU Cache Design and Canonical KeysCoding & Algorithms
- LRU Cache And O(1) Data StructuresCoding & Algorithms
- Cache And Versioned Data StructuresSoftware Engineering Fundamentals
- Concurrent Cache Design And Eviction
- Mutable Data Structures And O(1) DesignCoding & Algorithms