Design LRU Cache
Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2022-09-01
Problem Statement
Design and implement an in-memory LRU Cache that stores key-value pairs, supports fast lookups, insertions, and evictions based on the Least Recently Used (LRU) policy.
Functional Requirements (FR)
Basic Operations
•get(key) → Return value if the key exists; else return -1.
•put(key, value) → Insert a new key-value pair or update the value if key exists.
Capacity Constraint
•Cache has a fixed capacity.
•If capacity is exceeded, evict the least recently used item.
Usage Update
•Accessing a key (via get or put) marks it as most recently used.
Non-Functional Requirements (NFR)
•Time Complexity → O(1) for get and put.
•Space Complexity → O(capacity).
•Concurrency (Optional) → Handle multiple threads accessing the cache.
•Extensibility → Should allow changes to eviction policy (e.g., LFU, FIFO) in future.
Core Entities & Attributes
CacheNode
•key, value
•prev (pointer to previous node)
•next (pointer to next node)
LRUCache
•capacity
•map<Key, CacheNode> → for O(1) lookups
•head, tail → Doubly linked list to maintain LRU order
Core Components
HashMap / Dictionary
•Maps keys to nodes in the linked list for constant-time access.
Doubly Linked List
•Maintains usage order: head = most recently used, tail = least recently used.
•On access or insertion, move node to head.
•Eviction removes the tail node.
APIs / Operations
•get(key)
•If key exists: move node to head; return value.
•Else: return -1.
•put(key, value)
•If key exists: update value, move node to head.
•Else:
•If capacity is full: remove tail node.
•Add new node to head.
•remove(node) → Remove a node from the linked list.
•addToHead(node) → Add node to the head of the linked list.
LLD Design Goals
•Class Diagram → LRUCache, CacheNode.
•Design Patterns:
•Singleton (optional) → Single instance of cache in system.
•Strategy (optional) → For different eviction policies.
•Concurrency Handling → Use locks or concurrent structures for thread-safe operations.