Simulate a Cache with Recency-Based Eviction
Data Structure DesignAuto-graded · 23 test casesLast updated
Tests data structure design by building an in-memory cache that removes the least recently accessed entry when full.
Build a function that simulates an in-memory cache with a fixed capacity. When the cache reaches its limit and a new entry must be added, the entry that has gone the longest without being accessed is removed.
You are given:
capacity: a positive integer representing the maximum number of entries the cache can holdoperations: a list of operation names, each either"get"or"put"arguments: a list of argument lists, wherearguments[i]contains the arguments foroperations[i]- For a
"get"operation:[key] - For a
"put"operation:[key, value]
- For a
Process each operation in sequence:
get(key): If the key exists in the cache, return its value and mark it as recently accessed. If the key does not exist, return-1.put(key, value): Insert the key-value pair into the cache, or update the value if the key already exists. Either way, mark the key as recently accessed. If adding a new key would exceed the capacity, first remove the entry that has gone the longest without being accessed. ReturnNone(ornullin the output).
Return a list containing one result per operation: the retrieved value or -1 for each get, and None for each put.
Constraints
1 ≤ capacity ≤ 10⁴1 ≤ len(operations) ≤ 10⁵len(operations) == len(arguments)- All keys and values are integers in the range
[-10⁶, 10⁶] - Each operation is either
"get"or"put" - Both
getandputoperations must run in O(1) average time
Examples
Example 1
Input: simulate_recency_cache(2, ['put', 'put', 'get', 'put', 'get', 'get'], [[1, 1], [2, 2], [1], [3, 3], [2], [3]])
Output: [None, None, 1, None, -1, 3]
Example 2
Input: simulate_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 3
Input: simulate_recency_cache(1, ['put', 'get', 'put', 'get'], [[7, 10], [7], [8, 20], [7]])
Output: [None, 10, None, -1]
Hints
Hint 1
A hash map gives O(1) key lookups, but how do you track which entry is least recently used?
Hint 2
A doubly linked list can maintain access order, with the oldest entry at one end and the newest at the other. When an entry is accessed, move it to the fresh end.
Hint 3
Python's OrderedDict combines a hash map with ordering. Removing and reinserting a key moves it to the end, and popitem(last=False) removes the oldest.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To support O(1) access and eviction, combine two data structures:
- A hash map to look up keys instantly
- A doubly linked list to track access order, with the oldest entry at one end and the most recent at the other
When a key is accessed (via get or put), remove it from its current position in the list and reinsert it at the most-recent end. When the cache exceeds capacity, remove the entry at the oldest end.
Python's OrderedDict implements exactly this combination internally. It maintains insertion order and provides:
- O(1) average lookup and insertion (hash map)
- O(1) removal and reinsertion to refresh order (doubly linked list)
popitem(last=False)to remove the oldest entry
The algorithm:
- For each
get(key): if the key exists, pop it and reinsert it (moving it to the end), then return its value. Otherwise return-1. - For each
put(key, value): if the key exists, pop it first (to refresh its position). Then insert the key-value pair. If the size now exceeds capacity, remove the oldest entry withpopitem(last=False). ReturnNone.
Why It Works
The invariant is that entries in the OrderedDict are ordered from least to most recently accessed. Each operation maintains this:
- A
geton an existing key removes and reinserts it, placing it at the end (most recent). - A
puton an existing key does the same, updating its value. - A
puton a new key appends it at the end. - Eviction removes the first entry, which is the least recently accessed.
Since capacity is at least 1, a newly inserted or updated key is never immediately evicted.
Complexity
- Time: O(1) average per operation. Hash map operations (lookup, insert, delete) are O(1) average, and doubly linked list operations (unlink, append) are O(1) worst case. Processing n operations takes O(n) total.
- Space: O(capacity) for the cache, plus O(n) for the results list.
from collections import OrderedDict
from typing import List, Optional
def simulate_recency_cache(capacity: int, operations: List[str], arguments: List[List[int]]) -> List[Optional[int]]:
cache = OrderedDict()
results = []
for operation, args in zip(operations, arguments):
if operation == "get":
key = args[0]
if key not in cache:
results.append(-1)
else:
value = cache.pop(key)
cache[key] = value
results.append(value)
elif operation == "put":
key, value = args
if key in cache:
cache.pop(key)
cache[key] = value
if len(cache) > capacity:
cache.popitem(last=False)
results.append(None)
return results