LRU Cache

Medium

Topics
Hash TableLinked ListDesign

Design an LRU (Least Recently Used) cache with get(key) and put(key, value), both O(1). The constructor takes a positive capacity. get returns the value or -1; put inserts/updates and evicts the least recently used key when over capacity.

Example 1

returnsLRUCache(2)put(1, 1)put(2, 2)get(1)1put(3, 3)get(2)-1put(4, 4)get(1)-1get(3)3get(4)4
A cache with a fixed capacity. Reading a key counts as using it, so a get moves that key out of danger; when a put would overflow the capacity, the key that has gone longest without use is the one dropped. A get on a key that is absent or already evicted answers -1.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["LRUCache","put","put","get","put","get","put","get","get","get"], values = [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]
Output: [null,null,null,1,null,-1,null,-1,3,4]

Constraints

  • 1 <= capacity <= 3000
  • 0 <= key, value <= 10^4
  • At most 2*10^5 calls.
Editorial — intuition, approach, complexity and pitfalls

Intuition

You need O(1) lookup and O(1) recency updates. A hash map gives lookup; a doubly-linked list (or an ordered map) gives O(1) move-to-most-recent and eviction of the tail.

Approach

  1. Maintain a hash map from key to node and a doubly-linked list ordered by recency.
  2. On get/put, move the touched key to the most-recent end.
  3. On overflow, evict the least-recent (front) key.

Dry Run

LRUCache(2). The OrderedDict is kept oldest-first, so the least recently used
item is always at the front and `popitem(last=False)` evicts it.
  put 1 1   -> null         order  [(1,1)]
  put 2 2   -> null         order  [(1,1), (2,2)]
  get 1     -> 1            order  [(2,2), (1,1)]   -- the read MOVED 1 to the back
  put 3 3   -> null         order  [(1,1), (3,3)]   -- over capacity, 2 evicted
  get 2     -> -1           2 is gone
  put 4 4   -> null         order  [(3,3), (4,4)]   -- 1 evicted
  get 1     -> -1
  get 3     -> 3            order  [(4,4), (3,3)]
  get 4     -> 4            order  [(3,3), (4,4)]
answer null|null|null|1|null|-1|null|-1|3|4
The `get 1` row is the one that decides the whole sequence. A read is a USE, so it
refreshes recency, and that is why 2 is the victim at `put 3 3` rather than 1.
Drop `move_to_end` from get and 1 stays the oldest entry, so put 3 evicts it
instead -- the run then returns 2 at `get 2` where the answer is -1.
Eviction is checked after insertion, not before, which is why the dictionary is
briefly allowed to hold capacity + 1 entries. That ordering matters when the key
already exists: `put` on a present key must not evict anything, and here it
cannot, because the length does not grow.
Note put also refreshes recency for an existing key, via the same move_to_end.
Overwriting a value is a use too.

Complexity

  • Time — O(1): hash map + linked list give constant-time operations.
  • Space — O(capacity): stored entries.

Common Pitfalls

  • Update recency on get too, not just put.

Full Solution — all languages

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.cap = capacity
        self.cache = OrderedDict()
    def get(self, key):
        if key not in self.cache:
            return -1
        self.cache.move_to_end(key)
        return self.cache[key]
    def put(self, key, value):
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.cap:
            self.cache.popitem(last=False)
SensAI
Beta
Tap the mic to stop voice mode