download

Design an LRU cache with O(1) get and put

Algorithms~15 minReviewed 1 Nov 2026Free · No sign-in

Question

Write LRUCache(capacity) with two methods:

  • get(key) returns the value for key, or -1 if the key isn't in the cache.
  • put(key, value) adds the key or updates its value. If the cache now holds more than capacity keys, it drops the least recently used key: the one that nobody has read or written for the longest time.

Both methods must be O(1). With capacity 2: put("mug", 12), put("pen", 3), then get("mug") returns 12. Now put("cap", 9) drops pen, so get("pen") returns -1.

"CODE · PYTHON"
class LRUCache:
    def __init__(self, capacity):
        ...

    def get(self, key):
        ...

    def put(self, key, value):
        ...
Show hints (3)
  1. "WHAT YOU NEED"

    You need two things: find a key fast, and know which key was used least recently. A dict does the first. What keeps an order you can change in O(1)?

  2. "ORDER OF USE"

    Keep the keys in order of use: the oldest at the front, the newest at the end. A get hit and every put move the key to the end. Evict from the front.

  3. "ORDERED DICT"

    collections.OrderedDict has both moves: move_to_end(key) makes a key the newest, and popitem(last=False) removes the oldest. Both are O(1).

Show checked explanation

Keep the keys in an OrderedDict, from least to most recently used. get returns -1 on a miss. On a hit, move_to_end(key) makes the key the newest. put stores the value and calls move_to_end(key) too. If the cache is now too big, popitem(last=False) removes the oldest key. Each step is O(1).

"SOLUTION · PYTHON"
from collections import OrderedDict


class LRUCache:
    def __init__(self, capacity):
        self.capacity, self.items = capacity, OrderedDict()

    def get(self, key):
        if key in self.items:
            self.items.move_to_end(key)  # a hit makes it the newest
        return self.items.get(key, -1)

    def put(self, key, value):
        self.items[key] = value
        self.items.move_to_end(key)  # new or updated: now the newest
        if len(self.items) > self.capacity:
            self.items.popitem(last=False)  # drop the least recent


print(LRUCache(2).get("mug"))  # a miss returns -1
"OUTPUT"
-1

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

Here is the example with capacity 2, plus one update at the end. The order runs from the least recently used key to the newest.

callreturnsorder afterdropped
put("mug", 12)-mug-
put("pen", 3)-mug, pen-
get("mug")12pen, mug-
put("cap", 9)-mug, cappen
get("pen")-1mug, cap-
put("mug", 15)-cap, mug-

The third call is the one that matters. mug went in first, but get just read it, so it moved to the end. When cap arrives, pen is at the front and leaves. A cache that ignores reads would drop mug here.

The last call updates mug. Assigning to a key that is already in an OrderedDict keeps its old place, so put also calls move_to_end. Without it, mug would stay at the front and be the next key to go, although you just wrote it.

Why is every step O(1)? An OrderedDict is a hash table plus a doubly linked list of its keys. The hash table finds a key's list node. The list keeps the order. Moving a node to the end or removing the first node only changes a few links. A plain list would not work: order.remove(key) scans the list, which is O(n).

A plain dict also keeps insertion order. A hit becomes d[key] = d.pop(key), and the oldest key is next(iter(d)). It works, but move_to_end and popitem(last=False) say what you mean.

Common mistakes

  • Evicting in insertion order only. That is a FIFO queue, not LRU. In the example it drops mug when cap arrives, although get just read mug.
  • Counting uses and evicting the key with the fewest. That is LFU, a different policy, and finding the smallest count in a plain dict takes O(n).
  • Keeping the order in a list. Each hit needs order.remove(key), which scans the list, so every get costs O(n).
  • Evicting before you store the value. If the cache is full and you update a key that is already there, another key leaves for no reason.

Follow-up questions

  • "You can't use OrderedDict. How do you build it?" Keep a dict from key to node, and a doubly linked list with dummy head and tail nodes, so an empty list is never a special case. Each node also links to the previous node: to unlink a node in O(1), you must reach its neighbours on both sides.
  • "Is there an LRU cache in the standard library?" Yes. @functools.lru_cache(maxsize=128) caches a function's results by its arguments. It suits functions whose result depends only on their arguments. You can't remove or update one key: cache_clear() empties the whole cache.

What a strong answer covers

Names both parts: a hash map to find a key and a linked list to keep the order of use. Moves the key on every get hit and every put, and evicts only after storing. Uses move_to_end and popitem(last=False), and can build the linked list by hand.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from Crushing the Technical Interview (Keith Henning, 2025); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.