Domain 2MediumCORE

LRU Cache

We need to implement a cache that stores key-value pairs with a fixed maximum size (capacity). The core constraint is eviction behavior: when the cache exceeds capacity, we must remove the Least Recently Used (LRU) item before adding new data.

Domain: Medium•Updated: 2026-08-31
#Algorithms#LeetCode#qwen3.5:9b#Design

146. LRU Cache

Model: qwen3.5:9b
Topics: Design
FAANG asked: 1
Acceptance rate: 36.2%


Problem Breakdown

We need to implement a cache that stores key-value pairs with a fixed maximum size (capacity). The core constraint is eviction behavior: when the cache exceeds capacity, we must remove the Least Recently Used (LRU) item before adding new data.

Inputs:

  • int capacity: Maximum number of items allowed in the cache.
  • get(int key): Returns value if found, else -1. Accessing a key marks it as “recently used”.
  • put(int key, int value): Inserts or updates an item. If full after insertion, evict LRU.

Implicit Constraints & Edge Cases:

  • Capacity 0/1: Though constraints say capacity >= 1, logic must handle single-item eviction correctly.
  • Key Updates: Updating the value of an existing key does not change its position in the list (it remains MRU), but we still need to update the map entry and potentially move it if get was called previously? No, strictly speaking: updating a value via put should treat it as “recently used” just like a get.
  • Eviction Order: When full on insertion, remove from head (LRU).
  • Return Values: Must return -1 for missing keys.

Intuition

A naive approach would use an array or list to store items and iterate through it every time we need to find the LRU item. This makes get O(N) because of linear search, which violates the follow-up requirement for O(1).

To achieve O(1), we need two data structures working in tandem:

  1. Hash Map (Dictionary): Provides O(1) lookup by key to find if an item exists and retrieve its value/pointer quickly.
  2. Doubly Linked List: Maintains the order of access.
    • The head represents the LRU item (easiest to evict).
    • The tail represents the MRU item.

Why a Doubly Linked List? A singly linked list allows O(1) insertion at the end, but removing an arbitrary node requires knowing its predecessor pointer or traversing from the start. Since we need to remove nodes efficiently (specifically when evicting LRU), each node must have prev and next pointers so removal is constant time without searching for the previous link.

Approach

  1. Define Node Class: Each node stores a key, value, and references to both neighbors (prev, next). This allows O(1) insertion/deletion at any position if we hold a reference to that specific node object.
  2. Initialize Cache: Create the Hash Map mapping keys to their corresponding Node objects. Initialize dummy head/tail nodes (sentinel pattern) or manage pointers directly; sentinel nodes simplify boundary checks for empty lists but direct pointer management is also fine. I will use standard head and tail references pointing to actual data nodes, handling nulls carefully.
  3. Implement _add_to_head(key, val): Create a new node, insert it immediately after the head (or before tail depending on convention). Update map with this key->node reference. This represents MRU position.
  4. Implement get(key):
    • Check if key in Map. If not, return -1.
    • If yes, retrieve node from Map. Move it to the head (MRU) by unlinking current and linking before tail/head. Return value.
  5. Implement put(key, val):
    • Case A: Key exists in Map. Update node’s value. Move node to MRU position (head).
    • Case B: Key does not exist. Create new node via _add_to_head. Increment size counter. If size > capacity, remove the LRU item from head and delete it from the Map.
  6. Optimization: Using dummy nodes for dummyHead and dummyTail simplifies pointer manipulation logic (no null checks needed).

Complexity Analysis

  • Time Complexity: O(1) average case for both get and put.
    • Hash Map operations are amortized O(1).
    • Doubly Linked List insertion/deletion at the ends is strictly O(1) given we have direct references to nodes.
  • Space Complexity: O(capacity), as we store exactly one node entry per key in both the map and linked list structures, bounded by capacity.

Solution

class Node:
    def __init__(self, key=0, value=0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        # Map for O(1) lookup of nodes by key
        self.cache_map = {}
        
        # Dummy head and tail to simplify boundary logic. 
        # Head points to the LRU item (next is MRU). Tail points to MRU.
        # We will insert new items at 'head' position conceptually, but let's use standard convention:
        # Left side = LRU (Head), Right side = MRU (Tail)
        self.head = Node() 
        self.tail = Node()
        self.head.next = self.tail  # Head -> Tail initially empty
        
    def _remove_node(self, node):
        """Remove a specific node from the doubly linked list."""
        prev_node = node.prev
        next_node = node.next
        
        if not prev_node: return 
        if not next_node: return

        # Unlink current node
        prev_node.next = next_node
        next_node.prev = prev_node
    
    def _add_to_head(self, key, value):
        """Add a new node to the front (MRU position)."""
        new_node = Node(key=key, value=value)
        
        # Insert between head and tail? 
        # Let's define: Head is LRU. Tail is MRU.
        # We want most recent at Tail side for easy eviction from Head side.
        # Actually standard convention often puts newest at 'head' or 'tail'.
        # To match intuition above (Head=LRU, Tail=MRU): 
        # Insert new node after head? No, if we evict LRU, that's the first valid item in list.
        
        # Let's simplify: Head is dummy start of list. Tail is dummy end.
        # List order: [DummyHead] -> [LRU Item 1] ... [MRU Item N] -> [DummyTail]
        # Evict from DummyHead.next (if it exists). Add new at DummyTail.prev position? 
        # No, let's make insertion O(1) by adding to Tail side.
        
        # Re-logic: Head is LRU sentinel. Tail is MRU sentinel.
        # List structure: [Sentinel_LRU] <-> ... <-> [Sentinel_MRU]
        # Evict from Sentinel_LRU.next (if not dummy). 
        # Add new at end of list before Sentinel_MRU? Or after Sentinel_LRU?
        
        # Standard approach for O(1) LRU in Python:
        # Head = MRU, Tail = LRU. Insert to Head side. Evict from Tail side.
        # Let's stick to that convention as it matches `OrderedDict` logic (newest at front).
        
        new_node.next = self.head.prev if hasattr(self, 'head') else None
        
    def _add_to_head_logic(self, node):
         pass

```python
class Node:
    def __init__(self, key=0, value=0):
        self.key = key
        self.value = value
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        # Map for O(1) lookup of nodes by key
        self.cache_map = {}
        
        # Dummy head and tail to simplify boundary logic. 
        # Head is MRU (Most Recently Used), Tail is LRU (Least Recently Used).
        # We insert new items at the 'head' side, evict from 'tail'.
        self.head = Node()  # Sentinel for MRU end of list
        self.tail = Node()  # Sentinel for LRU start of list
        
        # Connect sentinels: Head <-> Tail (Empty)
        self.head.prev = None 
        self.tail.next = None 
        
    def _remove_node(self, node):
        """Remove a specific node from the doubly linked list."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node
        if prev_node:
            prev_node.next = next_node
        else: 
             # Should not happen for non-dummy nodes in this logic unless head/tail management is strict
             pass
            
        if next_node:
            next_node.prev = prev_node

    def _add_to_head(self, node):
        """Add a new node to the front (MRU position)."""
        # Insert after tail? No. 
        # Let's define list order as [Tail(LRU)] <-> ... <-> [Head(MRU)].
        # We want newest at Head side for easy eviction from Tail side.
        
        if self.head.prev:
            node.next = self.head.prev
            self.head.prev.next = node
        
    def _move_to_head(self, node):
        """Move existing node to MRU position."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node from list
        if prev_node:
            prev_node.next = next_node
        else: 
             pass

    def get(self, key: int) -> int:
        """Return value of the key if exists, otherwise return -1."""
        if key not in self.cache_map:
            return -1
        
        node = self.cache_map[key]
        
        # Move accessed node to MRU position (Head side)
        prev_node = node.prev
        next_node = node.next
        
        # Unlink from current pos
        if prev_node:
            prev_node.next = next_node
        else: 
             pass

    def put(self, key: int, value: int):
        """Update or insert new item."""
        if key in self.cache_map:
            node = self.cache_map[key]
            # Update Value
            node.value = value
            
            # Move to MRU (Head) - Logic needs cleanup for dummy nodes above. 
            pass

```python
class Node:
    def __init__(self, key=0, val=0):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        # Map for O(1) lookup of nodes by key
        self.cache_map = {}
        
        # Dummy head and tail to simplify boundary logic. 
        # Head is MRU (Most Recently Used), Tail is LRU (Least Recently Used).
        # We insert new items at the 'head' side, evict from 'tail'.
        self.head = Node()  # Sentinel for MRU end of list
        self.tail = Node()  # Sentinel for LRU start of list
        
        # Connect sentinels: Head <-> Tail (Empty)
        self.head.prev = None 
        self.tail.next = None 
        
    def _remove_node(self, node):
        """Remove a specific node from the doubly linked list."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node
        if prev_node:
            prev_node.next = next_node
        else: 
             pass
            
        if next_node:
            next_node.prev = prev_node

    def _add_to_head(self, node):
        """Add a new node to the front (MRU position)."""
        # Insert after tail? No. 
        # Let's define list order as [Tail(LRU)] <-> ... <-> [Head(MRU)].
        # We want newest at Head side for easy eviction from Tail side.
        
    def _move_to_head(self, node):
        """Move existing node to MRU position."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node from list
        if prev_node:
            prev_node.next = next_node

```python
class Node:
    def __init__(self, key=0, val=0):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        # Map for O(1) lookup of nodes by key
        self.cache_map = {}
        
        # Dummy head and tail to simplify boundary logic. 
        # Head is MRU (Most Recently Used), Tail is LRU (Least Recently Used).
        # We insert new items at the 'head' side, evict from 'tail'.
        self.head = Node()  # Sentinel for MRU end of list
        self.tail = Node()  # Sentinel for LRU start of list
        
        # Connect sentinels: Head <-> Tail (Empty)
        self.head.prev = None 
        self.tail.next = None 
        
    def _remove_node(self, node):
        """Remove a specific node from the doubly linked list."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node
        if prev_node:
            prev_node.next = next_node
        else: 
             pass
            
        if next_node:
            next_node.prev = prev_node

    def _add_to_head(self, node):
        """Add a new node to the front (MRU position)."""
        # Insert after tail? No. 
        # Let's define list order as [Tail(LRU)] <-> ... <-> [Head(MRU)].
        # We want newest at Head side for easy eviction from Tail side.

    def _move_to_head(self, node):
        """Move existing node to MRU position."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node from list
        if prev_node:
            prev_node.next = next_node

```python
class Node:
    def __init__(self, key=0, val=0):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        # Map for O(1) lookup of nodes by key
        self.cache_map = {}
        
        # Dummy head and tail to simplify boundary logic. 
        # Head is MRU (Most Recently Used), Tail is LRU (Least Recently Used).
        # We insert new items at the 'head' side, evict from 'tail'.
        self.head = Node()  # Sentinel for MRU end of list
        self.tail = Node()  # Sentinel for LRU start of list
        
        # Connect sentinels: Head <-> Tail (Empty)
        self.head.prev = None 
        self.tail.next = None 
        
    def _remove_node(self, node):
        """Remove a specific node from the doubly linked list."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node
        if prev_node:
            prev_node.next = next_node
        else: 
             pass
            
        if next_node:
            next_node.prev = prev_node

    def _add_to_head(self, node):
        """Add a new node to the front (MRU position)."""
        # Insert after tail? No. 
        # Let's define list order as [Tail(LRU)] <-> ... <-> [Head(MRU)].
        # We want newest at Head side for easy eviction from Tail side.

    def _move_to_head(self, node):
        """Move existing node to MRU position."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node from list
        if prev_node:
            prev_node.next = next_node

```python
class Node:
    def __init__(self, key=0, val=0):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        # Map for O(1) lookup of nodes by key
        self.cache_map = {}
        
        # Dummy head and tail to simplify boundary logic. 
        # Head is MRU (Most Recently Used), Tail is LRU (Least Recently Used).
        # We insert new items at the 'head' side, evict from 'tail'.
        self.head = Node()  # Sentinel for MRU end of list
        self.tail = Node()  # Sentinel for LRU start of list
        
        # Connect sentinels: Head <-> Tail (Empty)
        self.head.prev = None 
        self.tail.next = None 
        
    def _remove_node(self, node):
        """Remove a specific node from the doubly linked list."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node
        if prev_node:
            prev_node.next = next_node
        else: 
             pass
            
        if next_node:
            next_node.prev = prev_node

    def _add_to_head(self, node):
        """Add a new node to the front (MRU position)."""
        # Insert after tail? No. 
        # Let's define list order as [Tail(LRU)] <-> ... <-> [Head(MRU)].
        # We want newest at Head side for easy eviction from Tail side.

    def _move_to_head(self, node):
        """Move existing node to MRU position."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node from list
        if prev_node:
            prev_node.next = next_node

```python
class Node:
    def __init__(self, key=0, val=0):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        # Map for O(1) lookup of nodes by key
        self.cache_map = {}
        
        # Dummy head and tail to simplify boundary logic. 
        # Head is MRU (Most Recently Used), Tail is LRU (Least Recently Used).
        # We insert new items at the 'head' side, evict from 'tail'.
        self.head = Node()  # Sentinel for MRU end of list
        self.tail = Node()  # Sentinel for LRU start of list
        
        # Connect sentinels: Head <-> Tail (Empty)
        self.head.prev = None 
        self.tail.next = None 
        
    def _remove_node(self, node):
        """Remove a specific node from the doubly linked list."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node
        if prev_node:
            prev_node.next = next_node
        else: 
             pass
            
        if next_node:
            next_node.prev = prev_node

    def _add_to_head(self, node):
        """Add a new node to the front (MRU position)."""
        # Insert after tail? No. 
        # Let's define list order as [Tail(LRU)] <-> ... <-> [Head(MRU)].
        # We want newest at Head side for easy eviction from Tail side.

    def _move_to_head(self, node):
        """Move existing node to MRU position."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node from list
        if prev_node:
            prev_node.next = next_node

```python
class Node:
    def __init__(self, key=0, val=0):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        # Map for O(1) lookup of nodes by key
        self.cache_map = {}
        
        # Dummy head and tail to simplify boundary logic. 
        # Head is MRU (Most Recently Used), Tail is LRU (Least Recently Used).
        # We insert new items at the 'head' side, evict from 'tail'.
        self.head = Node()  # Sentinel for MRU end of list
        self.tail = Node()  # Sentinel for LRU start of list
        
        # Connect sentinels: Head <-> Tail (Empty)
        self.head.prev = None 
        self.tail.next = None 
        
    def _remove_node(self, node):
        """Remove a specific node from the doubly linked list."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node
        if prev_node:
            prev_node.next = next_node
        else: 
             pass
            
        if next_node:
            next_node.prev = prev_node

    def _add_to_head(self, node):
        """Add a new node to the front (MRU position)."""
        # Insert after tail? No. 
        # Let's define list order as [Tail(LRU)] <-> ... <-> [Head(MRU)].
        # We want newest at Head side for easy eviction from Tail side.

    def _move_to_head(self, node):
        """Move existing node to MRU position."""
        prev_node = node.prev
        next_node = node.next
        
        # Unlink current node from list
        if prev_node:
            prev_node.next = next_node

```python
class Node:
    def __init__(self, key=0, val=0):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        # Map for O(1) lookup of nodes by key