Simulate a Fixed-Capacity Recency-Eviction Cache
Data Structure DesignAuto-graded · 14 test casesLast updated
Tests whether you can combine a hash map and ordered structure to implement O(1) get/put with least-recently-used eviction on a bounded cache.
Fixed-Capacity Recency-Eviction Cache
You are building a simple in-memory cache that discards the entry used least recently whenever it runs out of room. Write a simulator that processes a sequence of named operations and returns the result of each one.
Operations
The simulator receives two parallel lists:
operations: a list of strings naming each operation.arguments: a list of argument lists, one per operation.
The three possible operations are:
"LRUCache" with arguments = [capacity]
Set up a fresh, empty cache with room for exactly capacity entries. Returns None.
"get" with arguments = [key]
Look up key in the cache.
- If
keyis present, return its associated value and mark it as the most recently used entry. - If
keyis absent, return-1. The cache is not modified.
"put" with arguments = [key, value]
Insert or update an entry.
- If
keyalready exists, overwrite its value and mark the entry as most recently used. - If
keyis new, insert it as the most recently used entry. If this causes the number of entries to exceedcapacity, remove the entry that was least recently used before this insertion.
Returns None.
Output
Return a list with one element per operation, preserving the original order. Operations that produce no value ("LRUCache" and "put") contribute None to the list.
Constraints
- The first operation is always
"LRUCache". 1 <= capacity <= 30000 <= key <= 10^40 <= value <= 10^5- The total number of operations is at most
2 × 10^5. - All operation strings are exactly one of
"LRUCache","get", or"put".
Examples
Example 1
Input: lru_cache_operations(['LRUCache', 'put', 'put', 'get', 'put', 'get'], [[2], [1, 1], [2, 2], [1], [3, 3], [2]])
Output: [None, None, None, 1, None, -1]
Example 2
Input: lru_cache_operations(['LRUCache', 'put', 'get', 'put', 'get', 'get'], [[1], [1, 10], [1], [1, 20], [1], [2]])
Output: [None, None, 10, None, 20, -1]
Hints
Hint 1
A plain dictionary gives O(1) key lookup but carries no ordering information. What extra structure could track which entry was touched least recently?
Hint 2
A doubly linked list lets you move any node to the front and remove the back node in O(1) — provided you already hold a direct pointer to that node. What gives you that pointer instantly for any key?
Hint 3
Python's collections.OrderedDict maintains insertion order and exposes move_to_end() and popitem(last=False), which map directly onto the recency operations you need.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core tension in this problem is that you need two things simultaneously:
- O(1) key lookup — find an entry by key instantly.
- O(1) recency ordering — on every access, promote the touched entry to "most recent"; on every eviction, remove the "least recent" entry instantly.
A plain dictionary handles (1) but has no ordering semantics. A list handles (2) in concept but requires O(n) to locate an arbitrary key. The classic solution wires both structures together: a hash map holds key → node for fast lookup, and a doubly linked list holds those nodes in recency order so that moving a node to the front, or removing the back node, costs only O(1) pointer updates.
Python's collections.OrderedDict is exactly this combined structure under the hood. It exposes two operations that map directly onto what you need:
move_to_end(key)— promotes an entry to the most-recently-used position.popitem(last=False)— removes and returns the least-recently-used entry (the front of the order).
Operation-by-operation reasoning
"LRUCache" — clears any previous state and records the new capacity. Nothing meaningful to return.
"get" — if the key is missing, return -1 and leave the cache unchanged. If it exists, call move_to_end to record the access, then return the stored value. Skipping move_to_end on a hit is a common bug: the entry's recency would stay frozen at its insertion time, causing it to be evicted too early.
"put" — two sub-cases:
- Key already exists: overwrite the value and call
move_to_end. Forgetting the move here is equally a bug. - Key is new: insert it (Python appends new keys at the back of an
OrderedDict, which is the "most recent" end whenlast=Falseevicts from the front). After inserting, iflen(cache) > capacity, callpopitem(last=False)to drop the oldest entry. Inserting before evicting is the clean invariant — it ensures a brand-new key is never immediately evicted.
Why it is correct
The OrderedDict maintains one invariant throughout: entries are ordered from least recently used (front) to most recently used (back). Every "get" hit and every "put" call explicitly moves the affected key to the back. The only entry ever removed is the front one, which is by definition the least recently used. Because OrderedDict manages the map and the ordering structure as a single unit, they are always in sync.
Complexity
- Time: O(1) average per operation. Each operation is a constant number of hash-table lookups and pointer updates.
- Space: O(capacity). At most
capacityentries are alive at any moment.
Full solution
from collections import OrderedDict
from typing import List, Optional
def lru_cache_operations(operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
cache: OrderedDict = OrderedDict()
capacity: int = 0
results: List[Optional[int]] = []
for op, args in zip(operations, arguments):
if op == "LRUCache":
capacity = args[0]
cache.clear()
results.append(None)
elif op == "get":
key = args[0]
if key not in cache:
results.append(-1)
else:
# Move to end = mark as most recently used
cache.move_to_end(key)
results.append(cache[key])
elif op == "put":
key, value = args[0], args[1]
if key in cache:
cache[key] = value
cache.move_to_end(key)
else:
cache[key] = value
if len(cache) > capacity:
# Remove the least recently used entry (front of the ordered dict)
cache.popitem(last=False)
results.append(None)
else:
raise ValueError(f"Unknown operation: {op}")
return results
Going deeper: the explicit linked-list version
OrderedDict is the idiomatic Python answer, but a natural follow-up is to build the structure by hand. The idea is to maintain:
- A
dictmapping each key to its doubly linked list node. - A linked list with two sentinel nodes (
headfor the MRU end,tailfor the LRU end). Sentinels eliminate all edge cases for inserting into or removing from an empty or single-element list.
Each node must store both the key and the value. Storing the key is critical: when you evict the tail's predecessor, you need its key to remove the corresponding entry from the dict. This is the detail candidates most often overlook.