Module 5.3⏱ 45 min read⚡ System Design & Data Structures
Design Systems (LRU & LFU Caches)
Combine hash maps with doubly linked lists to achieve $O(1)$ constant time complexity for Least Recently Used (LRU) cache operations.
1. The Architecture of High-Performance Caches
Cache eviction policies such as LRU (Least Recently Used) require two fundamental capabilities: $O(1)$ key-value lookups and $O(1)$ recency re-ordering upon access or insertion. While a standard hash map provides instant $O(1)$ lookups, it cannot track chronological access order. Conversely, a linked list tracks order sequentially but requires $O(n)$ traversal to find or update items.
The Hybrid Solution: Pairing a hash map with a doubly linked list solves both constraints. The hash map stores keys mapped directly to their corresponding list node pointers, enabling instant access while the doubly linked list handles constant-time node promotion and eviction.
2. Implementing LRU Cache Mechanics
To ensure all operations execute in $O(1)$ time, boundary dummy head and tail nodes are maintained:
Get Operation: If the key exists in the hash map, fetch its node, promote it to the front (right after the head), and return its value. If missing, return -1.
Put Operation: If the key exists, update its value and promote it to the front. If it doesn't exist, create a new node and insert it at the front. If capacity is exceeded, evict the node immediately preceding the tail before adding the new entry.