LRU Cache (LeetCode 146): Solution and Explanation

Medium
Hash Table
Linked List
Design
Doubly Linked List

Design a fixed-capacity key-value cache with get and put operations. Reading or writing a key marks it as the most recently used, and when an insert pushes the cache over capacity, the least recently used key is evicted. Both operations must run in O(1) average time.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A first attempt usually stores the pairs in a dictionary and keeps a separate list of keys in usage order. Lookups are fast, but moving a key to the end of the list on every access means finding it first, which is O(n). Another idea is to store a timestamp per key and scan for the smallest on eviction, which makes put O(n) instead.

To make every operation O(1), you need two abilities at once: find a key's entry instantly, and reorder or remove that entry instantly. A hash map gives the first. A doubly linked list gives the second, because once you hold a pointer to a node you can unlink it and splice it at the tail in constant time. The classic design keeps both: the map stores key to node, and the list keeps nodes in recency order with the least recently used at the head.

Python ships this exact combination as collections.OrderedDict, which is a dictionary backed by a doubly linked list. Its move_to_end marks a key as most recent, and popitem(last=False) removes the oldest one, both in O(1). The reference solution leans on it, and the Java and C++ versions build the same structure explicitly. In an interview, be ready to explain or write the linked list yourself, since that is what the question is really probing.

Approach: Hash map with ordered recency (OrderedDict)

  1. Store capacity and create an empty OrderedDict named cache. Its order runs from least to most recently used.
  2. In get, return -1 if the key is missing.
  3. Otherwise call move_to_end(key) to mark it as the most recent and return its value.
  4. In put, if the key already exists, move it to the end first so the update counts as a use.
  5. Assign cache[key] = value. A new key is appended at the most recent end automatically.
  6. If the size now exceeds capacity, call popitem(last=False) to evict the least recently used entry.

Step-by-step example

capacity = 2, then put(1,1), put(2,2), get(1), put(3,3), get(2), put(4,4), get(1), get(3), get(4)
  1. After put(1,1) and put(2,2), the order from oldest to newest is 1, 2.
  2. get(1) returns 1 and moves key 1 to the end, so the order is 2, 1.
  3. put(3,3) makes the size 3, so the oldest key, 2, is evicted. The order is 1, 3, and the following get(2) returns -1.
  4. put(4,4) overflows again and evicts key 1, leaving 3, 4. So get(1) returns -1.
  5. get(3) returns 3 and moves it to the end, then get(4) returns 4. The outputs match the expected [1, -1, -1, 3, 4].

Code: Python, Java, C++

1class LRUCache:
2    def __init__(self, capacity: int):
3        self.capacity = capacity
4        self.cache = OrderedDict()
5
6    def get(self, key: int) -> int:
7        if key not in self.cache:
8            return -1
9        self.cache.move_to_end(key)
10        return self.cache[key]
11
12    def put(self, key: int, value: int) -> None:
13        if key in self.cache:
14            self.cache.move_to_end(key)
15        self.cache[key] = value
16        if len(self.cache) > self.capacity:
17            self.cache.popitem(last=False)

Time and space complexity

Time

O(1) per operation

Dictionary lookups, move_to_end and popitem(last=False) all run in constant time on average, because the ordered dictionary unlinks and relinks list nodes it can find through the hash table.

Space

O(capacity)

The cache never holds more than capacity entries at the end of an operation, and each entry costs one map slot and one list node.

Other approaches

Hash map plus a hand-written doubly linked list (time O(1) per operation, space O(capacity))

Keep sentinel head and tail nodes, a map from key to node, and helpers to remove a node and insert one before the tail. This is the version interviewers usually expect and it is what the Java and C++ references implement.

Dictionary with timestamps (time O(capacity) per put, space O(capacity))

Store each key with the time of its last use and scan for the oldest timestamp when evicting. It is simple but makes each eviction O(capacity), which fails the O(1) requirement.

Common mistakes

  • Forgetting that get counts as a use. If you do not move the key on a read, the wrong entry gets evicted later.
  • Evicting before inserting when the key already exists. Updating an existing key never grows the cache, so only check capacity after the assignment.
  • In a hand-written list, removing a node from the list but not deleting its key from the map, or the reverse. The two structures must always agree.
  • Using a singly linked list. Unlinking a node in O(1) needs its predecessor, which only a doubly linked list gives you directly.

Frequently asked questions

Why does an LRU cache use a hash map and a doubly linked list?

The hash map finds any entry in O(1), and the doubly linked list can move or remove a known node in O(1). Neither alone supports both fast lookups and fast reordering, but together they make every operation constant time.

Is using OrderedDict allowed in an interview?

Many interviewers accept it if you explain that it is a hash map backed by a doubly linked list. Some will then ask you to implement the list yourself, so it is worth practicing both versions.

What is the difference between LRU and LFU caching?

LRU evicts the entry that was used longest ago, while LFU evicts the entry used the fewest times, breaking ties by recency. LFU needs extra bookkeeping, usually a map from frequency to an ordered set of keys.

How would you make an LRU cache thread-safe?

Wrap get and put in a lock, because both mutate the ordering. For heavy concurrency, real systems shard the cache into several independently locked segments or use approximate recency to reduce contention.