LRU Cache

Design a Least Recently Used cache with O(1) get and put.

Pattern

Hash Map + Doubly Linked List

This problem follows the Hash Map + Doubly Linked List pattern, commonly found in the Linked List category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Hash map for O(1) lookup. Doubly linked list for O(1) move-to-front and eviction.

Key Insight

The hash map gives O(1) lookup, the doubly linked list gives O(1) reordering — together they make both get and put O(1).

Step-by-step

  1. 1Use a hash map for O(1) key lookup
  2. 2Use a doubly linked list to track access order
  3. 3On get: if key exists, move node to front (most recent), return value
  4. 4On put: if key exists, update and move to front; if new, add to front
  5. 5If over capacity, remove the tail node (least recently used)

Pseudocode

class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.map = {}  # key -> node
        self.head, self.tail = Node(0,0), Node(0,0)
        self.head.next, self.tail.prev = self.tail, self.head

    def get(self, key):
        if key in self.map:
            self._moveToFront(self.map[key])
            return self.map[key].val
        return -1

    def put(self, key, val):
        if key in self.map:
            self.map[key].val = val
            self._moveToFront(self.map[key])
        else:
            node = Node(key, val)
            self.map[key] = node
            self._addToFront(node)
            if len(self.map) > self.cap:
                lru = self.tail.prev
                self._remove(lru)
                del self.map[lru.key]
Complexity Analysis

Time Complexity

O(1)

Space Complexity

O(capacity)
More Linked List Problems

Master this pattern with YeetCode

Practice LRU Cache and similar Linked List problems with flashcards. Build pattern recognition through active recall.

Practice this problem