The LRU (Least Recently Used) Cache is a classic technical interview problem that tests your understanding of data structures and algorithmic trade-offs. In this article, we break down why a simple HashMap or array falls short, and how combining a HashMap with a doubly linked list yields an efficient solution.
Why HashMap Alone Isn't Enough
A HashMap provides O(1) lookups, but it doesn't track the order in which items are accessed. To evict the least recently used item, you need a way to know which item was used least recently—something a HashMap alone cannot do efficiently.
The Problem with Arrays and Linked Lists
Using an array to maintain order would require O(n) shifts when updating an item's position. A singly linked list can track order but finding a specific node for access still takes O(n) time.
The Optimal Solution: HashMap + Doubly Linked List
By combining a HashMap with a doubly linked list, you get the best of both worlds:
- The HashMap provides O(1) access to any node.
- The doubly linked list maintains the recency order, allowing O(1) insertion and removal of nodes.
When an item is accessed, move its node to the head of the list. When the cache is full, remove the node at the tail and delete it from the HashMap.
What Interviewers Evaluate
- Understanding of trade-offs (time vs. space)
- Ability to implement O(1) operations
- Handling edge cases: empty cache, duplicate keys, capacity limits
Mastering LRU Cache shows you think like an engineer, not just a coder.