LRU Cache design
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2020-03-11
Problem Statement
Design an LRU (Least Recently Used) Cache that efficiently supports constant-time retrieval and updates, and automatically evicts the least recently used items when the cache reaches its capacity.
Functional Requirements (FR)
Cache Operations
•get(key) – Retrieve the value for a key if it exists; otherwise return null/exception.
•put(key, value) – Add a key-value pair to the cache. If the key already exists, update its value.
Eviction Policy
•When the cache reaches its maximum capacity, evict the least recently used (LRU) item.
Capacity Management
•Initialize cache with a fixed maximum capacity.
Optional Features
•Support for TTL (time-to-live) for cache entries.
•Thread-safe operations for concurrent access.
Suggested Classes & Responsibilities
Class: LRUCache
•Attributes:
•capacity → maximum number of entries
•map → HashMap<Key, Node> for O(1) access
•head & tail → pointers for doubly linked list to track LRU order
•Methods:
•get(key) → fetch value and move node to front of list
•put(key, value) → insert or update; move node to front; evict tail if full
•removeNode(node) → helper to remove node from linked list
•addToFront(node) → helper to insert node at front of list
Class: Node
•Attributes: key, value, prev, next
Data Flow (High-Level)
1.get(key) → check HashMap:
•If key exists → move node to head (most recently used) → return value.
•If key doesn’t exist → return null.
2.put(key, value) → check HashMap:
•If key exists → update value → move node to head.
•If key doesn’t exist → create node → add to head → update HashMap.
•If capacity exceeded → remove tail node (LRU) → delete from HashMap.
Key Design Considerations
•Time Complexity: Ensure O(1) for get and put using HashMap + Doubly Linked List.
•Memory Efficiency: Linked list nodes and map should not exceed cache capacity.
•Thread Safety: Consider synchronized blocks or ConcurrentHashMap for multi-threaded use.
•Extensibility: Can extend to support TTL, cache statistics (hits/misses), or distributed LRU.