LRU Cache
LeetCode 146 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Hash map + doubly linked list with sentinels.
मैंने LRU Cache (LeetCode 146) ऐसे हल किया — Design पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
You need O(1) lookup and O(1) 'move to most recent' / 'evict least recent'. A hash map finds nodes; a doubly linked list keeps recency order — the most recent sits after head, the least recent before tail.
Approach
- 1
get: if present, move the node to the front and return its value.
- 2
put: remove an existing node; if full, remove tail.prev.
- 3
Insert the new node after head and record it in the map.
मैंने कैसे हल किया
Hash map + doubly linked listPythonO(1) per op
class Node:
def __init__(self,key,val):
self.key = key
self.val = val
self.prev=None
self.next=None
class LRUCache:
def __init__(self, capacity: int):
self.capacity = capacity
self.head = Node(0,0)
self.tail = Node(0,0)
self.head.next = self.tail
self.tail.prev = self.head
self.loc_mpp = {}
def get(self, key: int) -> int:
if key in self.loc_mpp:
node = self.loc_mpp.get(key)
self.remove(node)
self.insert(node)
return node.val
return -1
def put(self, key: int, value: int) -> None:
if key in self.loc_mpp:
node = self.loc_mpp[key]
self.remove(node)
if len(self.loc_mpp)==self.capacity:
self.remove(self.tail.prev)
node = Node(key,value)
self.insert(node)
def insert(self,new_node) -> None:
#head - next node
#head - new_node -> next_node
self.loc_mpp[new_node.key]=new_node
next_node = self.head.next
new_node.next = next_node
next_node.prev = new_node
self.head.next = new_node
new_node.prev=self.head
def remove(self,old_node) -> None:
del self.loc_mpp[old_node.key]
#prev_node old_node next_node
prev_node = old_node.prev
next_node = old_node.next
prev_node.next = next_node
next_node.prev = prev_node
# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)LRU Cache — अक्सर पूछे जाने वाले प्रश्न
LRU Cache के पीछे intuition क्या है?
You need O(1) lookup and O(1) 'move to most recent' / 'evict least recent'. A hash map finds nodes; a doubly linked list keeps recency order — the most recent sits after head, the least recent before tail.
LRU Cache (LeetCode 146) कैसे हल करें?
1. get: if present, move the node to the front and return its value. 2. put: remove an existing node; if full, remove tail.prev. 3. Insert the new node after head and record it in the map.
LRU Cache की time और space complexity क्या है?
Time: O(1) per operation। Space: O(capacity)। (Accepted approach: Hash map + doubly linked list।)
LRU Cache में आम गलतियाँ क्या हैं?
Sentinel head and tail remove all null checks. Store the key in the node so eviction can delete it from the map.