Fixed-Capacity Eviction Cache with Recency Tracking
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests whether you can design a cache that evicts the least recently accessed entry in O(1) time by combining a hash map with an ordered structure.
Problem
You need to build a fixed-size cache that always evicts the entry that was least recently touched when space runs out.
Implement a function that drives such a cache through a sequence of operations and returns the results.
def run_recency_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]
Cache Behaviour
The cache holds at most capacity key-value pairs (both integers). It supports two operations:
get key
- If
keyis present, return its value and mark it as the most recently used entry. - If
keyis absent, return-1. The recency order of all other entries stays unchanged.
put key value
- If
keyalready exists, overwrite its value and mark it as the most recently used entry. The total number of entries does not change, so nothing is evicted. - If
keyis new, insert the pair. If the cache now holds more thancapacityentries, immediately evict the entry that was least recently used (i.e. the one untouched for the longest time).
A successful get and any put both count as "using" an entry. A failed get (key not found) does not affect recency.
Function Contract
capacity— the maximum number of entries the cache may hold at one time.operations— a list of strings, each either"get"or"put". There is no constructor entry in this list.arguments— parallel list of argument arrays. A"get"entry has one element (the key); a"put"entry has two elements (key, then value).- Return a list with one element per operation, in order. A
"get"produces its integer result (-1if missing). A"put"producesNone. Any unknown operation name must raiseValueError.
Constraints
1 <= capacity <= 30000 <= key <= 10 0000 <= value <= 100 000- At most
2 × 10⁵calls togetorputin total. - Each
get/putmust run in O(1) average time.
Examples
Example 1
Input: run_recency_cache(2, ['put', 'put', 'get', 'put', 'get', 'put', 'get', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]])
Output: [None, None, 1, None, -1, None, -1, 3, 4]
Example 2
Input: run_recency_cache(2, ['get', 'put', 'get'], [[1], [1, 10], [1]])
Output: [-1, None, 10]
Hints
Hint 1
A plain dict gives O(1) lookup but no ordering. A plain list gives ordering but O(n) lookup. Think about which Python built-in fuses both properties, or how you would fuse them yourself.
Hint 2
When you move a node to the 'most recent' position, you need O(1) access to its neighbours so you can stitch them together. What kind of linked list supports that?
Hint 3
Each node in the list must store its own key, not just its value. Ask yourself: when you evict the tail node, how do you know which map entry to delete?
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core tension is that we need two things at once:
- O(1) lookup by key — a hash map gives us that.
- O(1) access to the oldest entry — a structure that preserves insertion order gives us that, as long as we always append new or refreshed entries at one end.
We track recency by convention: the back of the ordered structure is always the most recently used entry, and the front is always the least recently used one. Every time an entry is touched — whether by a successful get or a put — we move it to the back. Eviction always removes from the front.
Why OrderedDict works
Python's collections.OrderedDict is a hash map internally backed by a doubly linked list, so every operation it exposes is O(1):
pop(key)removes an entry by key in O(1).- Reassigning
cache[key] = valueafter a pop reinserts at the back. popitem(last=False)removes and returns the front (oldest) entry in O(1).
Those three building blocks are all we need.
Operation-by-operation walkthrough
get key
- If the key is absent, append
-1to the result. Do nothing else — recency order must not change. - If the key is present,
popit, reinsert it (moving it to the back), and append its value.
put key value
- If the key already exists,
popit first so the upcoming insert lands at the back rather than staying in its old position. - Insert
cache[key] = value(always lands at the back). - If
len(cache) > capacity, callpopitem(last=False)to evict the front entry. - Append
Noneto the result.
Note that updating an existing key never increases the cache size, so step 3 only triggers for genuinely new keys.
Why it is correct
Two invariants hold after every operation:
- Order = recency. Reading the ordered dict from front to back gives keys from least to most recently used, because every access appends to the back and we never reorder entries in any other way.
- Size ≤ capacity. We check after every
putand evict at most one entry, so the count never exceeds the limit.
A failed get intentionally leaves the structure untouched — a subtle but important point. Only touches that successfully retrieve or store a value influence recency.
Complexity
| Time | Space | |
|---|---|---|
Per get or put | O(1) average | — |
| Full sequence of n operations | O(n) | O(capacity) for the cache, O(n) for the output list |
Edge cases
capacity = 1: everyputof a new key immediately evicts the previous one.- Updating an existing key: recency refreshes, value updates, size stays the same — no eviction.
value = 0: perfectly valid; never use truthiness to check presence. Always usekey in cacheor.get().geton a missing key: returns-1and leaves everything else alone.- Unknown operation: raises
ValueError.
Reference solution
from collections import OrderedDict
from typing import List, Optional
def run_recency_cache(
capacity: int,
operations: List[str],
arguments: List[List[int]],
) -> List[Optional[int]]:
cache: OrderedDict[int, int] = OrderedDict()
result: List[Optional[int]] = []
for operation, args in zip(operations, arguments):
if operation == "get":
key = args[0]
if key not in cache:
result.append(-1)
else:
value = cache.pop(key)
cache[key] = value # reinsert at the end = most recent
result.append(value)
elif operation == "put":
key, value = args
if key in cache:
cache.pop(key) # remove so reinsertion moves it to end
cache[key] = value
if len(cache) > capacity:
cache.popitem(last=False) # drop the oldest (front) entry
result.append(None)
else:
raise ValueError(f"unknown operation: {operation!r}")
return result
Going deeper: building the linked list manually
If you are asked to implement the underlying structure yourself, the approach is:
- Maintain a doubly linked list where each node stores both its key and its value.
- Keep a
dictmapping each key to its node directly. - Two sentinel nodes (
headandtail) eliminate all special cases for empty or single-element lists. - "Move to front" is always: unlink the node (two pointer updates via
prev/next), then relink it right afterhead(four pointer updates). - On eviction, unlink
tail.prevand delete its key from the dict — which is why each node must store its key, not just its value.
This gives the same O(1) per operation with O(capacity) space, and is the answer an interviewer asking you to "build it from scratch" is looking for.