Design Cache (LRU Cache) - Code for LRU Cache

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2024-10-16

Problem Statement

Design a Least Recently Used (LRU) Cache that stores key-value pairs in memory. When capacity is reached, it evicts the least recently used item. Focus on OOP design, efficient operations, and modularity.


Functional Requirements


1.Basic Operations
•get(key) → return value if key exists; else return -1.
•put(key, value) → insert or update a key-value pair. Evict LRU key if capacity exceeded.
2.Eviction Policy
•LRU: Remove the least recently accessed item when cache is full.
3.Optional Features
•Thread-safety for concurrent access.
•Metrics: cache hits, misses.


Non-Functional Requirements


•Performance: O(1) for get and put.
•Memory Efficiency: Use data structures to optimize space usage.
•Extensibility: Easy to switch eviction strategy to LFU, FIFO, etc.


Design Hints


•Key Classes / Interfaces
•LRUCache → main class exposing get and put.
•DoublyLinkedList → store key-value nodes in order of usage.
•Node → represents a cache entry with key, value, prev, and next.
•Data Structures
•HashMap / Dictionary → O(1) access to nodes by key.
•Doubly Linked List → maintain access order, support O(1) addition/removal.
•Design Pattern
•Combination of HashMap + Doubly Linked List → standard for LRU Cache.


Example Flow


1.LRUCache cache = LRUCache(2)
2.put(1, 1) → cache = {1=1}
3.put(2, 2) → cache = {1=1, 2=2}
4.get(1) → returns 1, cache order updated: {2=2, 1=1}
5.put(3, 3) → evicts 2, cache = {1=1, 3=3}


Python Implementation

1 2class Node: 3 def __init__(self, key, value): 4 self.key = key 5 self.value = value 6 self.prev = None 7 self.next = None 8 9class LRUCache: 10 def __init__(self, capacity: int): 11 self.capacity = capacity 12 self.cache = {} # key -> node 13 # Dummy head and tail 14 self.head = Node(0, 0) 15 self.tail = Node(0, 0) 16 self.head.next = self.tail 17 self.tail.prev = self.head 18 19 def _remove(self, node): 20 prev_node = node.prev 21 next_node = node.next 22 prev_node.next = next_node 23 next_node.prev = prev_node 24 25 def _add_to_front(self, node): 26 node.next = self.head.next 27 node.prev = self.head 28 self.head.next.prev = node 29 self.head.next = node 30 31 def get(self, key: int) -> int: 32 if key in self.cache: 33 node = self.cache[key] 34 self._remove(node) 35 self._add_to_front(node) 36 return node.value 37 return -1 38 39 def put(self, key: int, value: int) -> None: 40 if key in self.cache: 41 self._remove(self.cache[key]) 42 node = Node(key, value) 43 self._add_to_front(node) 44 self.cache[key] = node 45 if len(self.cache) > self.capacity: 46 # Remove LRU node 47 lru = self.tail.prev 48 self._remove(lru) 49 del self.cache[lru.key] 50 51# Example Usage 52cache = LRUCache(2) 53cache.put(1, 1) 54cache.put(2, 2) 55print(cache.get(1)) # Output: 1 56cache.put(3, 3) # Evicts key 2 57print(cache.get(2)) # Output: -1 58cache.put(4, 4) # Evicts key 1 59print(cache.get(1)) # Output: -1 60print(cache.get(3)) # Output: 3 61print(cache.get(4)) # Output: 4


This LLD problem tests:


•OOP design: Node, Doubly Linked List, Cache separation
•Efficient operations: O(1) get and put
•Eviction policy: Correct LRU handling
•Extensibility: Can swap eviction strategy if needed


Solution

Comments