LRU Cache Simulator with Recency and Grouped Views
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulates an LRU cache through a sequence of put, get, and snapshot operations, testing recency bookkeeping, eviction, and ordered grouping of values.
You are given a fixed-capacity cache and a list of operations to run against it, in order. Each operation returns one result. Your job is to simulate the cache and return the list of results.
Let capacity be the maximum number of entries the cache may hold. The cache keeps a recency order: the entry that was used most recently is "most recent," and the entry that was used least recently is "least recent."
The operations are given as two parallel lists: operations[i] is the name of the operation, and arguments[i] is its argument list.
| Operation | Arguments | Effect | Result |
|---|---|---|---|
"put" | [key, value] | Insert the key, or overwrite its value if it already exists. Either way the key becomes the most recent entry. If the cache now holds more than capacity entries, remove the least recent entry. | None |
"get" | [key] | If the key is present, make it the most recent entry and return its value. If it is absent, change nothing. | The value, or None if the key is absent |
"snapshot" | [] | Read-only. Produce one line per entry in the form key: value, ordered from most recent to least recent. Join the lines with "\n". | A string (empty string if the cache is empty) |
"compressed_snapshot" | [] | Read-only. Group the entries by value and produce one line per group in the form value [k1, k2, ...], joined with "\n". | A string (empty string if the cache is empty) |
Rules for the compressed view
- Scan the entries from most recent to least recent. A group is created when its value is first encountered, so groups are ordered by the recency of their most recent member.
- Within a group, the keys are listed from most recent to least recent.
- Keys are joined with
", "inside the brackets. - Values are compared with
==, so values that compare equal (for example1,1.0, andTrue) belong to the same group. The label printed for a group is the first value encountered for it during the scan. - Values are rendered with
str(), the same way an f-string would render them.
Other rules
- Snapshot operations do not change recency. Only
putand a successfulgetdo. - A
geton a missing key returnsNoneand changes nothing. - Overwriting an existing key with
putcounts as a use. It never causes eviction, because the number of entries does not change. - If
capacityis0, everyputis immediately evicted, so the cache always stays empty.
Constraints
0 <= capacity <= 10^5len(operations) == len(arguments), and both are at most10^5- Every operation is one of
"put","get","snapshot", or"compressed_snapshot" - Keys are non-empty strings
- Values can be any printable objects that support
== - Results must be returned in the same order as the operations
Examples
Example 1
Input: simulate_lru_snapshots(2, ['put', 'put', 'snapshot', 'compressed_snapshot'], [['A', 2], ['B', 2], [], []])
Output: [None, None, 'B: 2\nA: 2', '2 [B, A]']
Example 2
Input: simulate_lru_snapshots(2, ['put', 'put', 'get', 'put', 'snapshot', 'compressed_snapshot'], [['A', 1], ['B', 2], ['A'], ['C', 1], [], []])
Output: [None, None, 1, None, 'C: 1\nA: 1', '1 [C, A]']
Hints
Hint 1
Keep the entries in an ordered structure where the front is the least recent entry and the back is the most recent. Moving an existing key to the back and removing from the front should both be constant time.
Hint 2
Snapshots only read the structure. Iterate over the entries in reverse to get most-recent-first order, and do not move anything.
Hint 3
For the compressed view, scan the entries from most recent to least recent and append each key to the group for its value. Create a new group the first time a value appears, so group order follows first appearance.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep the cache in an OrderedDict, ordered from least recent at the front to most recent at the back.
put: assign the value, then callmove_to_endso the key becomes most recent. If the size is now abovecapacity, callpopitem(last=False)to remove the least recent entry. This is correct because the key just written sits at the back and is never the one removed, unless capacity is 0.get: if the key is missing, returnNoneand leave everything alone. Otherwise move the key to the back and return its value.snapshot: read the items in reverse, which gives most-recent-first order. Format each askey: valueand join with newlines. Nothing is moved.compressed_snapshot: walk the same reversed order once. For each entry, find the existing group with an equal value and append the key to it. If there is none, create a new group at the end. Groups therefore appear in the order their value is first seen from the most recent side, and keys within a group keep recency order.
Why it is correct
- Recency invariant: the order of the
OrderedDictalways reflects true recency. Onlyputand a successfulgetreorder anything, and each moves exactly one key to the back. - Eviction: eviction happens only after the new key has been moved to the back, so the front element is always the true least recent entry.
- Compression: every entry is visited exactly once in recency order and appended to exactly one group. Groups are created in scan order, so the group ordering rule holds, and keys inside each group stay in recency order.
Complexity
Let n be the number of entries currently stored (at most capacity) and g the number of distinct values.
putandget: O(1) amortized.snapshot: O(n) time and space.compressed_snapshot: O(n · g) time because of the linear group search. This search uses only==, so it also works for unhashable values. If values are hashable, a dictionary from value to group index brings this down to O(n).- Storage: O(capacity).
Edge cases
- Empty cache: both snapshots return
"". capacity == 0: eachputinserts and then evicts immediately, so the cache remains empty.- Overwriting an existing key: refreshes recency and never evicts.
- Missing key on
get: returnsNonewith no side effects. - Values that compare equal, such as
1,1.0, andTrue, share one group, labeled by the first value seen.
Reference solution
from collections import OrderedDict
from typing import List
def simulate_lru_snapshots(capacity: int, operations: List[str], arguments: List[List[object]]) -> List[object]:
cache = OrderedDict() # front = least recent, back = most recent
results = []
for operation, args in zip(operations, arguments):
if operation == "put":
key, value = args
cache[key] = value
cache.move_to_end(key)
if len(cache) > capacity:
cache.popitem(last=False)
results.append(None)
elif operation == "get":
key = args[0]
if key in cache:
cache.move_to_end(key)
results.append(cache[key])
else:
results.append(None)
elif operation == "snapshot":
entries = list(cache.items())[::-1]
results.append("\n".join(f"{key}: {value}" for key, value in entries))
elif operation == "compressed_snapshot":
groups = [] # list of [label_value, [keys]] in order of first appearance
for key, value in reversed(list(cache.items())):
for group in groups:
if group[0] == value:
group[1].append(key)
break
else:
groups.append([value, [key]])
results.append("\n".join(f"{label} [{', '.join(keys)}]" for label, keys in groups))
else:
raise ValueError(f"Unknown operation: {operation}")
return results