STOP 33 · DESIGN & BITS
Caches, Random Access, and Streaming Indexes
LRU: hash map plus doubly linked list O(1) get and put
- Learn first
- Leads to
- No later stop builds on it.
- How often asked
- asked by 29 companies · in 40 reportsAmazon 5, TikTok / ByteDance 4, Microsoft 3, Apple 2, Oracle 2
Warm up with this one
LC 146LRU CacheStuck? Peek at the approach
Combine a hash table and a doubly linked list for O(1) access, updates, and eviction while maintaining recency order.
Key points
- The hash map finds a node in O(1); the doubly linked list moves it to the front and drops the tail in O(1).
- A get counts as a use and moves the node to the most recent end; put on an existing key updates and moves it instead of inserting a second copy.
- When you must hand-roll the list, sentinel head and tail nodes remove every null check.
Common pitfalls
- Evicting the tail from the list but not from the map, or the other way round.
- Decide once whether you insert then evict or evict then insert, and think through edge cases such as capacity 0.
- Without the key stored in the list node you can't tell which map entry to delete on eviction.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
LRU cache · hash map + doubly linked list
Capacity 2: put(1, 1), put(2, 2), get(1), put(3, 3), get(2), put(4, 4), get(1), get(3), get(4)
Try your own input
- Capacity
- 2
- Size
- 0
- Operation
- —
The hash map (cells) finds a key’s list node; the doubly linked list runs from most to least recently used, between two sentinels.
InvariantThe list runs from most to least recently used; the map and the list always hold the same keys, at most capacity of them.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 146, with it.
Python
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity: int):
self.cap = capacity
self.data = OrderedDict() # a hash map over a doubly linked list; the end is most recent
def get(self, key: int) -> int:
if key not in self.data:
return -1
self.data.move_to_end(key) # mark as most recently used
return self.data[key]
def put(self, key: int, value: int) -> None:
self.data[key] = value
self.data.move_to_end(key)
if len(self.data) > self.cap:
self.data.popitem(last=False) # evict the least recently usedC++
class LRUCache {
int cap;
list<pair<int, int>> items; // front = most recently used
unordered_map<int, list<pair<int, int>>::iterator> pos; // key -> its node in items
public:
LRUCache(int capacity) : cap(capacity) {}
int get(int key) {
auto it = pos.find(key);
if (it == pos.end()) return -1;
items.splice(items.begin(), items, it->second); // move to front in O(1)
return it->second->second;
}
void put(int key, int value) {
if (auto it = pos.find(key); it != pos.end()) {
it->second->second = value;
items.splice(items.begin(), items, it->second);
return;
}
items.emplace_front(key, value);
pos[key] = items.begin();
if ((int)items.size() > cap) {
pos.erase(items.back().first); // evict the least recently used
items.pop_back();
}
}
};Java
// LinkedHashMap in access order is a hash map over a doubly linked list.
class LRUCache extends LinkedHashMap<Integer, Integer> {
private final int cap;
LRUCache(int capacity) {
super(16, 0.75f, true); // accessOrder = true: every get moves the entry to the end
cap = capacity;
}
int get(int key) {
return getOrDefault(key, -1);
}
@Override
protected boolean removeEldestEntry(Map.Entry<Integer, Integer> eldest) {
return size() > cap; // evict the least recently used after an insert
}
}Go
import "container/list"
type entry struct{ key, value int }
type LRUCache struct {
cap int
order *list.List // front = most recently used
pos map[int]*list.Element // key -> its element in order
}
func NewLRUCache(capacity int) *LRUCache {
return &LRUCache{cap: capacity, order: list.New(), pos: map[int]*list.Element{}}
}
func (c *LRUCache) Get(key int) int {
el, ok := c.pos[key]
if !ok {
return -1
}
c.order.MoveToFront(el)
return el.Value.(*entry).value
}
func (c *LRUCache) Put(key, value int) {
if el, ok := c.pos[key]; ok {
el.Value.(*entry).value = value
c.order.MoveToFront(el)
return
}
c.pos[key] = c.order.PushFront(&entry{key, value})
if c.order.Len() > c.cap {
oldest := c.order.Back() // evict the least recently used
c.order.Remove(oldest)
delete(c.pos, oldest.Value.(*entry).key)
}
}Common variants
Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Two heaps: a max-heap below, a min-heap aboveO(log n) insert · O(1) median
For a running median of a stream (or the k-th smallest, or a sliding-window median): keep the smaller half in a max-heap and the larger half in a min-heap. Each insert goes into the max-heap, its top moves to the min-heap, and then the max-heap is topped up so it is never the smaller one. The median sits on the two tops. LC 295 (Find Median from Data Stream).
Python
import heapq
class MedianFinder:
"""Running median of a stream of numbers (LC 295)."""
def __init__(self):
self.low: list[int] = [] # the smaller half, negated so heapq gives a max-heap
self.high: list[int] = [] # the larger half, a min-heap
def add(self, x: int) -> None:
heapq.heappush(self.low, -x)
heapq.heappush(self.high, -heapq.heappop(self.low)) # the largest of low moves up
if len(self.high) > len(self.low): # low keeps the same size or one more
heapq.heappush(self.low, -heapq.heappop(self.high))
def median(self) -> float:
if len(self.low) > len(self.high):
return -self.low[0]
return (-self.low[0] + self.high[0]) / 2C++
// Running median of a stream of numbers (LC 295).
class MedianFinder {
priority_queue<int> low; // the smaller half, largest on top
priority_queue<int, vector<int>, greater<int>> high; // the larger half, smallest on top
public:
void add(int x) {
low.push(x);
high.push(low.top()); // the largest of low moves up
low.pop();
if (high.size() > low.size()) { // low keeps the same size or one more
low.push(high.top());
high.pop();
}
}
double median() const {
return low.size() > high.size() ? low.top() : ((double)low.top() + high.top()) / 2;
}
};Java
// Running median of a stream of numbers (LC 295).
class MedianFinder {
private final PriorityQueue<Integer> low = new PriorityQueue<>(Comparator.reverseOrder()); // the smaller half
private final PriorityQueue<Integer> high = new PriorityQueue<>(); // the larger half
void add(int x) {
low.offer(x);
high.offer(low.poll()); // the largest of low moves up
if (high.size() > low.size()) low.offer(high.poll()); // low keeps the same size or one more
}
double median() {
return low.size() > high.size() ? low.peek() : ((double) low.peek() + high.peek()) / 2;
}
}Go
import "container/heap"
// intHeap is a container/heap of ints in the order less gives.
type intHeap struct {
xs []int
less func(a, b int) bool
}
func (h *intHeap) Len() int { return len(h.xs) }
func (h *intHeap) Less(i, j int) bool { return h.less(h.xs[i], h.xs[j]) }
func (h *intHeap) Swap(i, j int) { h.xs[i], h.xs[j] = h.xs[j], h.xs[i] }
func (h *intHeap) Push(x any) { h.xs = append(h.xs, x.(int)) }
func (h *intHeap) Pop() any {
x := h.xs[len(h.xs)-1]
h.xs = h.xs[:len(h.xs)-1]
return x
}
// MedianFinder keeps the running median of a stream of numbers (LC 295).
type MedianFinder struct {
low, high *intHeap
}
func NewMedianFinder() *MedianFinder {
return &MedianFinder{
low: &intHeap{less: func(a, b int) bool { return a > b }}, // the smaller half, largest on top
high: &intHeap{less: func(a, b int) bool { return a < b }}, // the larger half, smallest on top
}
}
func (m *MedianFinder) Add(x int) {
heap.Push(m.low, x)
heap.Push(m.high, heap.Pop(m.low)) // the largest of low moves up
if m.high.Len() > m.low.Len() { // low keeps the same size or one more
heap.Push(m.low, heap.Pop(m.high))
}
}
func (m *MedianFinder) Median() float64 {
if m.low.Len() > m.high.Len() {
return float64(m.low.xs[0])
}
return float64(m.low.xs[0]+m.high.xs[0]) / 2
}Array plus index map: delete by swapping with the lastO(1) average per operation · O(n) space
For O(1) insert and delete plus O(1) random pick (or access by position): keep the values in an array and each value's index in a hash map. To delete, move the last element into the freed slot, update its index and pop the end, so the array never has holes. LC 380 (Insert Delete GetRandom O(1)); LC 381 allows duplicates.
Python
import random
class RandomizedSet:
"""insert, remove and get_random in O(1) on average (LC 380)."""
def __init__(self):
self.items: list[int] = [] # the values, in no particular order
self.where: dict[int, int] = {} # value -> its index in items
def insert(self, x: int) -> bool:
if x in self.where:
return False
self.where[x] = len(self.items)
self.items.append(x)
return True
def remove(self, x: int) -> bool:
if x not in self.where:
return False
i, last = self.where.pop(x), self.items.pop()
if i < len(self.items): # x was not last: the last value fills its slot
self.items[i] = last
self.where[last] = i
return True
def get_random(self) -> int:
return random.choice(self.items)C++
// insert, remove and getRandom in O(1) on average (LC 380).
class RandomizedSet {
vector<int> items; // the values, in no particular order
unordered_map<int, int> where; // value -> its index in items
public:
bool insert(int x) {
if (where.count(x)) return false;
where[x] = items.size();
items.push_back(x);
return true;
}
bool remove(int x) {
auto it = where.find(x);
if (it == where.end()) return false;
int i = it->second, last = items.back();
items[i] = last; // the last value fills x's slot (x itself if it was last)
where[last] = i;
items.pop_back();
where.erase(x);
return true;
}
int getRandom() const { return items[rand() % items.size()]; }
};Java
// insert, remove and getRandom in O(1) on average (LC 380).
class RandomizedSet {
private final List<Integer> items = new ArrayList<>(); // the values, in no particular order
private final Map<Integer, Integer> where = new HashMap<>(); // value -> its index in items
private final Random random = new Random();
boolean insert(int x) {
if (where.containsKey(x)) return false;
where.put(x, items.size());
items.add(x);
return true;
}
boolean remove(int x) {
Integer i = where.get(x);
if (i == null) return false;
int last = items.get(items.size() - 1);
items.set(i, last); // the last value fills x's slot (x itself if it was last)
where.put(last, i);
items.remove(items.size() - 1);
where.remove(x);
return true;
}
int getRandom() {
return items.get(random.nextInt(items.size()));
}
}Go
import "math/rand"
// RandomizedSet supports Insert, Remove and GetRandom in O(1) on average (LC 380).
type RandomizedSet struct {
items []int // the values, in no particular order
where map[int]int // value -> its index in items
}
func NewRandomizedSet() *RandomizedSet { return &RandomizedSet{where: map[int]int{}} }
func (s *RandomizedSet) Insert(x int) bool {
if _, ok := s.where[x]; ok {
return false
}
s.where[x] = len(s.items)
s.items = append(s.items, x)
return true
}
func (s *RandomizedSet) Remove(x int) bool {
i, ok := s.where[x]
if !ok {
return false
}
last := s.items[len(s.items)-1]
s.items[i] = last // the last value fills x's slot (x itself if it was last)
s.where[last] = i
s.items = s.items[:len(s.items)-1]
delete(s.where, x)
return true
}
func (s *RandomizedSet) GetRandom() int { return s.items[rand.Intn(len(s.items))] }Why it works
- The list order is the recency order: every get or put moves the node to the front, so the tail is always the least recently used entry, and evicting it is exactly LRU.
- The map and the list stay in sync: each key maps to exactly one node in the list, and every insert, move and delete updates both, so get never finds an evicted node.
- A doubly linked list with sentinels unlinks a node by rewiring its two neighbours in O(1), with no search for the predecessor.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
LRU 缓存我用哈希表加双向链表。哈希表从键 O(1) 找到节点,链表按最近使用排序,头部最新、尾部最旧。get 命中就把节点移到头部;put 已有的键就更新并移到头部,否则插到头部,超出容量就删掉尾部节点,并从哈希表里一起删掉。手写链表时加头尾哨兵,所有操作都不用判空,get 和 put 都是 O(1)。For an LRU cache I combine a hash map with a doubly linked list. The map finds a key's node in O(1), and the list is ordered by recency, newest at the head and oldest at the tail. A hit on get moves the node to the head; put on an existing key updates it and moves it, otherwise it inserts at the head and, past capacity, removes the tail node from both the list and the map. With sentinel head and tail nodes there are no null checks, and get and put are both O(1).Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
from collections import OrderedDict
class LRUCache: self.data.popitem(last=False)Practice by stage
This stop's 12 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Core 8
| # | Problem | Approach | Rating |
|---|---|---|---|
| 146 | LRU Cache | Combine a hash table and a doubly linked list for O(1) access, updates, and eviction while maintaining recency order. | |
| 380 | Insert Delete GetRandom O(1) | Use an array and a position map for uniform random access, swapping with the last element for O(1) removal. | |
| 703 | Kth Largest Element in a Stream | Maintain the stream's k largest values in a size-k min-heap, handling fewer than k initial values and duplicate insertions, and explain O(log k) updates. | |
| 295 | Find Median from Data Stream | Use two heaps for the lower and upper halves of a stream, explaining both heap-size and heap-top ordering invariants. | |
| 981 | Time Based Key-Value Store | Keep timestamp-ordered versions per key and binary-search the predecessor, handling queries earlier than the first version. | |
| 1146 | Snapshot Array | Implement snapshots with sparse per-index version logs and coalesce repeated writes within the same snapshot. | |
| 2080 | Range Frequency Queries | Build an inverted index from values to sorted positions and answer static range-frequency queries with two binary searches. | |
| 362 | Design Hit Counter 🔒 | Aggregate hits by time window, handling multiple events in the same second and the exact expiration boundary. |
Advanced 4
| # | Problem | Approach | Rating |
|---|---|---|---|
| 460 | LFU Cache | Combine frequency buckets with LRU order within each frequency, maintaining the minimum frequency and correctly updating existing keys. | |
| 381 | Insert Delete GetRandom O(1) - Duplicates allowed | Extend the position map to sets of indices to preserve removal behavior and sampling probabilities with duplicate elements. | |
| 2353 | Design a Food Rating System | Maintain group rankings under dynamic updates and explain stale-record handling in ordered sets or lazy heaps. | |
| 432 | All O`one Data Structure | Use adjacent frequency buckets to support increments, decrements, and minimum/maximum keys while keeping multiple structures consistent. |
Core Skills
Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.
- LRU CacheMedium