LRU Cache

Pattern: LRU and LFU cache

medium

Use a hash map from key to node and a doubly linked list ordered from most to least recently used. get and put move the node to the front; when full, put removes the node before the tail and its key from the map. Everything is O(1).

The problem

Build LRUCache(capacity) with get(key) (the value, or -1) and put(key, value) (insert or update). Both count as a use. When a new key would exceed the capacity, first evict the least recently used key. Both operations must be O(1).

Think first

  • What does each operation need to find in O(1)?
  • Which structure keeps an order and allows moving any item to the front in O(1)?
  • When evicting, how do you remove the key from the map?

Hints

    Brute force, and why it fails

    Keep a timestamp per key and scan for the oldest on eviction: O(n) per put.

    The key insight

    A map gives direct access to nodes; a doubly linked list keeps the recency order with O(1) moves. Dummy head and tail nodes remove the edge cases.

    Dry run

    order2 1

    LRUCache(2). put(1, 1), put(2, 2). Order: 2, 1 (most recent first).

    Step 1 of 4

    The plan

    get(key):  node = map.get(key) or return -1
               move node to the front; return node.value
    put(key, value):
               if key in map: update, move to the front, return
               if size == capacity: remove tail.prev from list and map
               add a new node at the front and to the map
    

    Complexity

    Time
    O(1) per operation
    Space
    O(capacity)

    Each operation does one map lookup and a constant number of pointer changes.

    Edge cases

    • Capacity 1: every new key evicts the old one.
    • put on an existing key when full: no eviction.
    • get of a missing key: -1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class LRUCache {
        private static class Node {
            int key, val;
            Node prev, next;
            Node(int key, int val) { this.key = key; this.val = val; }
        }
    
        private final int capacity;
        private final Map<Integer, Node> map = new HashMap<>();   // key -> its node in the list
        private final Node head = new Node(0, 0), tail = new Node(0, 0);   // most recent after head, least recent before tail
    
        public LRUCache(int capacity) {
            this.capacity = capacity;
            head.next = tail;
            tail.prev = head;
        }
    
        public int get(int key) {
            Node node = map.get(key);
            if (node == null) return -1;
            unlink(node);
            addFront(node);                         // it is now the most recently used
            return node.val;
        }
    
        public void put(int key, int value) {
            Node node = map.get(key);
            if (node != null) {                     // update and mark as most recent
                node.val = value;
                unlink(node);
                addFront(node);
                return;
            }
            if (map.size() == capacity) {           // evict the least recently used, just before tail
                Node lru = tail.prev;
                unlink(lru);
                map.remove(lru.key);
            }
            node = new Node(key, value);
            map.put(key, node);
            addFront(node);
        }
    
        private void unlink(Node n) {
            n.prev.next = n.next;
            n.next.prev = n.prev;
        }
    
        private void addFront(Node n) {
            n.next = head.next;
            n.prev = head;
            head.next.prev = n;
            head.next = n;
        }
    }

    C++

    class LRUCache {
    public:
        int capacity;
        list<pair<int, int>> items;                 // {key, value}, most recently used at the front
        unordered_map<int, list<pair<int, int>>::iterator> where;   // key -> its position in the list
    
        LRUCache(int capacity) : capacity(capacity) {}
    
        int get(int key) {
            auto it = where.find(key);
            if (it == where.end()) return -1;
            items.splice(items.begin(), items, it->second);   // move to the front in O(1)
            return it->second->second;
        }
    
        void put(int key, int value) {
            auto it = where.find(key);
            if (it != where.end()) {                // update and mark as most recent
                it->second->second = value;
                items.splice(items.begin(), items, it->second);
                return;
            }
            if (static_cast<int>(items.size()) == capacity) {   // evict the least recently used, at the back
                where.erase(items.back().first);
                items.pop_back();
            }
            items.push_front(make_pair(key, value));
            where[key] = items.begin();
        }
    };

    Python

    from lib import DNode
    
    
    class LRUCache:
        def __init__(self, capacity: int):
            self.capacity = capacity
            self.map = {}                           # key -> its node in the list
            self.head, self.tail = DNode(0), DNode(0)   # most recent after head, least recent before tail
            self.head.next, self.tail.prev = self.tail, self.head
    
        def get(self, key: int) -> int:
            node = self.map.get(key)
            if node is None:
                return -1
            self._unlink(node)
            self._add_front(node)                   # it is now the most recently used
            return node.val[1]
    
        def put(self, key: int, value: int) -> None:
            node = self.map.get(key)
            if node is not None:                    # update and mark as most recent
                node.val = (key, value)
                self._unlink(node)
                self._add_front(node)
                return
            if len(self.map) == self.capacity:      # evict the least recently used, just before tail
                lru = self.tail.prev
                self._unlink(lru)
                del self.map[lru.val[0]]
            node = DNode((key, value))
            self.map[key] = node
            self._add_front(node)
    
        def _unlink(self, n) -> None:
            n.prev.next, n.next.prev = n.next, n.prev
    
        def _add_front(self, n) -> None:
            n.next, n.prev = self.head.next, self.head
            self.head.next.prev = n
            self.head.next = n

    Common mistakes

    • Evicting before checking whether the key already exists.
    • Forgetting to move the node on get.
    • Leaving the evicted key in the map.

    Similar problems