Build a Fixed-Size Cache That Forgets the Least-Used Entry
Data Structure DesignAuto-graded · 21 test casesLast updated
Tests your ability to combine a hash map and an ordered structure to implement O(1) reads and writes with recency-based eviction.
Problem
You need to implement a fixed-capacity cache that evicts the entry touched least recently whenever it runs out of room.
The cache supports two operations:
fetch(key)— Return the stored value forkey, or-1if it is not in the cache. A successful fetch counts as a use of that key.store(key, value)— Writevalueforkey. Ifkeyis already in the cache, update its value and refresh its recency. If the cache is already full andkeyis new, drop the least recently used entry first, then insert the new one.
Both operations must run in O(1) average time.
How Your Solution Is Evaluated
Your class is driven by a single function that receives:
capacity— the maximum number of entries the cache may hold at once.operations— a list of strings, each either"get"or"put".arguments— a parallel list of argument lists:- For
"get", the inner list holds one integer:[key]. - For
"put", the inner list holds two integers:[key, value].
- For
The function must return a list with one element per operation:
- For each
"get", the element is the integer result (-1if the key is absent). - For each
"put", the element isNone.
Operations are applied in order, and each one may affect the outcome of later ones.
Constraints
1 ≤ capacity ≤ 10000 ≤ key, value ≤ 10^41 ≤ len(operations) ≤ 10^4- Every
"get"entry inoperationshas exactly one integer in the correspondingargumentsentry. - Every
"put"entry inoperationshas exactly two integers in the correspondingargumentsentry. - The value
0is a valid cached value; do not confuse it with a missing key.
Examples
Example 1
Input: run_cache_operations(2, ['put', 'put', 'get', 'put', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2]])
Output: [None, None, 1, None, -1]
Hints
Hint 1
You need O(1) lookup by key and O(1) identification of the least-recently-used entry at the same time — think about which two data structures, combined, give you both properties at once.
Hint 2
A doubly linked list maintains order cheaply: moving a node to the front costs a fixed number of pointer rewrites, with no shifting. Pair it with a hash map from key to node and you have both O(1) access and O(1) order updates.
Hint 3
Add a dummy sentinel node at each end of the list so you never have to handle empty-list or single-node edge cases. The node just before the tail sentinel is always the eviction target. Crucially, store the key inside each node so you can remove the map entry when you evict.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core idea
Two requirements pull in different directions:
- Find any key instantly. Only a hash map gives you O(1) lookup.
- Know which entry was used longest ago, and update that ordering cheaply. A doubly linked list lets you splice a node out and reattach it at the front in a fixed number of pointer writes, with no searching.
Combining them — a hash map from key to list node, and a doubly linked list ordered from most- to least-recently-used — satisfies both in O(1).
Data structure layout
- The list runs from a dummy head sentinel (most-recent end) to a dummy tail sentinel (least-recent end).
- Every real node sits between the two sentinels and stores its
key, itsvalue, andprev/nextpointers. - The map stores
key → node. - Sentinels eliminate every "is the list empty?" branch: the node at
tail.previs always the eviction candidate, even when only one real entry exists. - Each node carries its own
keyso that, when it is evicted from the tail end, you know which map entry to delete.
Operation walkthrough
fetch(key) / "get"
- Key absent → append
-1, change nothing. - Key present → remove the node from its current position, reattach it immediately after the head sentinel (marking it most-recent), return its value.
store(key, value) / "put"
- Key already exists → update the value in place, move the node to the front, append
None. Size is unchanged, so no eviction check is needed. - Key is new → create a node, add it to the map, insert it at the front. If the map now exceeds
capacity, remove the node attail.prevand delete its key from the map. AppendNone.
Inserting before evicting is safe: the new node is at the front, so it can never be the one removed even when capacity == 1.
Why it is correct
The invariant is list order = recency order. Every operation that touches a key — hit or write — moves that key to the front. So the node just before the tail is always the one untouched for the longest time, which is precisely what LRU eviction requires.
A few details worth noting:
- A
"get"miss does not alter recency. It leaves the list and map unchanged. - A
"put"on an existing key refreshes recency even though no eviction can occur. Forgetting this step is the most common bug. - Value
0is valid. Treat key absence as the signal for a miss, not a falsy value check.
Python shortcut
collections.OrderedDict is a hash map backed by a doubly linked list. move_to_end(key) promotes a key to most-recent; popitem(last=False) removes the least-recent. The behavior is identical to building the linked list by hand, so the reference solution uses it for clarity.
Complexity
| Time | Space | |
|---|---|---|
Each "get" or "put" | O(1) average | — |
n total operations | O(n) | O(capacity) for cache + O(n) for output |
The hash operations are amortised O(1); the pointer rewrites for list manipulation are a small constant.
Edge cases
- Empty cache, first call is
"get"→ returns-1immediately. capacity == 1→ every new key evicts the previous one; updating the same key just refreshes it.- Repeated
"get"on the same key → each call moves the node to the front; it stays the most-recent entry. "put"on an existing key with the same value → still counts as a use; recency must be refreshed.
Reference solution
from collections import OrderedDict
from typing import List, Optional
def run_cache_operations(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
cache: OrderedDict = OrderedDict()
results: List[Optional[int]] = []
for operation, args in zip(operations, arguments):
if operation == "get":
key = args[0]
if key not in cache:
results.append(-1)
else:
cache.move_to_end(key)
results.append(cache[key])
else:
key, value = args
if key in cache:
cache.move_to_end(key)
cache[key] = value
if len(cache) > capacity:
cache.popitem(last=False)
results.append(None)
return results