Call-Signature Cache with Least-Recently-Used Eviction
Data Structure DesignAuto-graded · 17 test casesLast updated
Simulate a fixed-capacity LRU cache keyed by a call's positional and keyword arguments, with order-insensitive, type-aware key matching.
Call-Signature Cache
You are simulating a cache that remembers the results of function calls. A call is identified by its positional arguments (a list) and its keyword arguments (a dictionary). The cache holds at most capacity entries. When it overflows, it discards the least recently used entry.
Implement a function that processes a sequence of operations on an initially empty cache and returns one result per operation.
Operations
Operation i is operations[i], with its data in arguments[i]:
| Operation | arguments[i] | Effect | Result |
|---|---|---|---|
"put" | [positional, keyword, value] | Store value under the call identified by positional and keyword. | None |
"get" | [positional, keyword] | Look up the call. | The stored value, or None if the call is not in the cache |
"size" | [] | Report how many entries are currently stored. | That count |
"clear" | [] | Remove every entry. | None |
Rules
- Call identity. Two calls are the same entry exactly when their positional lists are equal and their keyword dictionaries are equal, under these rules:
- The order of keys in a dictionary does not matter. This applies to the top-level keyword dictionary and to dictionaries nested at any depth.
- The order of items in a list does matter, at any depth.
- Values are compared with their types.
1,1.0andtrueare three different values.[1]and1are different.nullis different from every other value. - Positional and keyword arguments are separate. Moving a value from one to the other produces a different call.
- Recency. A
put(whether it inserts a new entry or overwrites an existing one) and a successfulgetboth make that entry the most recently used. Agetthat misses changes nothing.sizeandcleardo not affect recency of any other entries. - Overwrite. A
putfor an existing call replaces its value and does not change the size. - Eviction. If a
putof a new call makes the number of entries exceedcapacity, remove the single least recently used entry. The entry just inserted counts as the most recently used. - A stored value may itself be
None. In that case a hit and a miss both returnNone, but a hit still refreshes recency.
Input
capacity: maximum number of entries.operations: list of operation names, each one of"put","get","size","clear".arguments: list of the same length asoperations. Each element has the shape given in the table. Positional lists and keyword dictionaries contain only JSON-style values:null, booleans, integers, floats, strings, lists, and dictionaries with string keys.
Output
A list with one result per operation, in order.
Constraints
1 <= capacity <= 10000 <= len(operations) <= 10^4len(arguments) == len(operations)- Argument structures are finite and contain only the JSON-style types listed above.
- Stored values can be any JSON-style value.
- Each get/put should run in O(1) time apart from the cost of examining the arguments of that call.
Examples
Example 1
Input: run_call_cache(2, ['put', 'put', 'get', 'put', 'get', 'get'], [[[1], {}, 10], [[2], {}, 20], [[1], {}], [[3], {}, 30], [[2], {}], [[3], {}]])
Output: [None, None, 10, None, None, 30]
Example 2
Input: run_call_cache(2, ['put', 'put', 'get', 'get', 'size'], [[[1, 2], {'x': 1, 'y': [2, 3]}, 5], [[1, 2], {'y': [2, 3], 'x': 1}, 6], [[1, 2], {'x': 1, 'y': [2, 3]}], [[1, 2], {'x': 1, 'y': [2, 4]}], []])
Output: [None, None, 6, None, 1]
Example 3
Input: run_call_cache(1, ['put', 'put', 'get', 'get', 'put', 'get'], [[[], {'a': [1, {'b': 2}]}, 7], [[], {'a': [1, {'b': 2}]}, 8], [[], {'a': [1, {'b': 2}]}], [[], {'a': [1, {'b': 3}]}], [['z'], {}, 9], [[], {'a': [1, {'b': 2}]}]])
Output: [None, None, 8, None, None, None]
Hints
Hint 1
Build a single hashable key from (positional, keyword). Convert each value recursively into a tagged tuple so that lists, dicts, ints, floats and booleans cannot collide with each other.
Hint 2
For dictionaries, produce a tuple of (key, converted value) pairs sorted by key so that insertion order is irrelevant. Do not sort lists.
Hint 3
Use a hash map from key to a node in a doubly linked list with sentinel head and tail nodes. Moving a node to the most-recent end and evicting the node next to the other sentinel are both O(1).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
There are two sub-problems: deciding when two calls are "the same", and keeping entries in recency order with O(1) updates.
1. Canonical keys. Convert (positional, keyword) into a nested tuple that is hashable and has the right notion of equality.
- Each value becomes a tagged tuple:
("int", 1),("float", 1.0),("bool", True),("str", "a"),("none",). The tag keeps1,1.0andTrueapart, even though Python considers them equal. - A list becomes
("list", (frozen items...)), in the original order. - A dict becomes
("dict", (sorted (key, frozen value) pairs)), sorted by key. This makes key order irrelevant at every nesting level.
2. O(1) LRU structure. Keep a hash map from the frozen key to a node in a doubly linked list. The list has sentinel head and tail nodes, with the least recently used node right after the head and the most recently used right before the tail.
gethit: unlink the node, re-append it before the tail, return its value.puton an existing key: update the value and move the node to the recent end.puton a new key: append the node and, if the map now exceedscapacity, unlinkhead.nextand delete it from the map.size:lenof the map.clear: empty the map and reconnect the sentinels.
Why it is correct
- Frozen keys are equal exactly when the original arguments are equal under the stated rules. Tags separate types, list order is preserved, and dict items are sorted.
- The list is always ordered from least to most recently used, because every put and every successful get moves its node to the recent end. Eviction therefore removes the right entry.
- The sentinels remove empty-list and single-node special cases.
Complexity
- Per operation, linked-list and map work is O(1). Building the key costs O(S) for the size of the arguments, plus a sort of each dictionary's keys.
- Space is O(capacity x average entry size).
Reference solution
from typing import List
class _Node:
__slots__ = ("key", "value", "prev", "next")
def __init__(self, key=None, value=None):
self.key = key
self.value = value
self.prev = None
self.next = None
def _freeze(value):
if value is None:
return ("none",)
if isinstance(value, bool):
return ("bool", value)
if isinstance(value, int):
return ("int", value)
if isinstance(value, float):
return ("float", value)
if isinstance(value, str):
return ("str", value)
if isinstance(value, list):
return ("list", tuple(_freeze(item) for item in value))
if isinstance(value, dict):
items = [(str(k), _freeze(v)) for k, v in value.items()]
items.sort(key=lambda kv: kv[0])
return ("dict", tuple(items))
raise TypeError("arguments must contain JSON-compatible values")
def run_call_cache(capacity: int, operations: List[str], arguments: List[List[object]]) -> List[object]:
table = {}
head = _Node()
tail = _Node()
head.next = tail
tail.prev = head
def unlink(node):
node.prev.next = node.next
node.next.prev = node.prev
def push_recent(node):
node.prev = tail.prev
node.next = tail
tail.prev.next = node
tail.prev = node
def make_key(positional, keyword):
return (_freeze(positional), _freeze(keyword))
results = []
for op, data in zip(operations, arguments):
if op == "put":
positional, keyword, value = data
key = make_key(positional, keyword)
node = table.get(key)
if node is not None:
node.value = value
unlink(node)
push_recent(node)
else:
node = _Node(key, value)
table[key] = node
push_recent(node)
if len(table) > capacity:
oldest = head.next
unlink(oldest)
del table[oldest.key]
results.append(None)
elif op == "get":
positional, keyword = data
key = make_key(positional, keyword)
node = table.get(key)
if node is None:
results.append(None)
else:
unlink(node)
push_recent(node)
results.append(node.value)
elif op == "size":
results.append(len(table))
elif op == "clear":
table.clear()
head.next = tail
tail.prev = head
results.append(None)
else:
raise ValueError("unknown operation")
return results