Simulate LRU Cache with Composite Keys
Data Structure DesignAuto-graded · 17 test casesLast updated
Tests understanding of LRU eviction policy, composite key normalization, and cache statistics tracking through command simulation.
You are building a simulator for an LRU (Least Recently Used) cache that handles complex keys. The cache must support three operations:
Operations:
-
get: Retrieve or store a value for a given key. If the key exists in the cache, return the stored value and mark it as recently used. If the key does not exist, store the provided value and return it. This counts as a cache hit or miss respectively. -
clear: Remove all entries from the cache and reset hit/miss counters to zero. -
cache_info: Return current cache statistics as a dictionary with keys"hits","misses","maxsize", and"currsize".
Key Normalization:
Keys can be composite structures (lists, dicts, tuples, sets) and must be normalized so that semantically equivalent structures map to the same cache entry:
- Dictionaries with the same key-value pairs are equivalent regardless of insertion order
- Lists and tuples are compared by position
- Sets are equivalent if they contain the same elements
LRU Eviction:
When inserting a new entry would exceed maxsize, evict the least recently used entry first. If maxsize is 0, never store anything (always miss).
Function Signature:
def simulate_lru_cache(maxsize: int, operations: List[str], arguments: List[List]) -> List:
Parameters:
maxsize: Maximum number of entries the cache can hold (0 means no caching)operations: List of operation names ("get","clear", or"cache_info")arguments: Parallel list of arguments for each operation- For
"get":[key, value]wherekeyis the lookup key andvalueis the value to store on miss - For
"clear"and"cache_info": empty list[]
- For
Returns:
A list of results, one per operation:
"get": the cached or newly stored value"clear":None"cache_info": dictionary with"hits","misses","maxsize","currsize"
Constraints:
- 1 ≤
len(operations)≤ 1000 - 0 ≤
maxsize≤ 100 - Keys may contain nested lists, dicts, tuples, and sets up to 5 levels deep
- All values are JSON-serializable primitives or structures
len(operations)==len(arguments)
Examples
Example 1
Input: simulate_lru_cache(2, ['get', 'get', 'get', 'cache_info', 'get', 'cache_info', 'clear', 'cache_info'], [[[1], 10], [[2], 20], [[1], 99], [], [[3], 30], [], [], []])
Output: [10, 20, 10, {'hits': 1, 'misses': 2, 'maxsize': 2, 'currsize': 2}, 30, {'hits': 1, 'misses': 3, 'maxsize': 2, 'currsize': 2}, None, {'hits': 0, 'misses': 0, 'maxsize': 2, 'currsize': 0}]
Example 2
Input: simulate_lru_cache(1, ['get', 'get', 'get', 'cache_info'], [[[1, {'b': 2, 'a': 1}], 5], [[1, {'a': 1, 'b': 2}], 99], [[2], 7], []])
Output: [5, 5, 7, {'hits': 1, 'misses': 2, 'maxsize': 1, 'currsize': 1}]
Example 3
Input: simulate_lru_cache(0, ['get', 'get', 'cache_info'], [[['x'], 1], [['x'], 2], []])
Output: [1, 2, {'hits': 0, 'misses': 2, 'maxsize': 0, 'currsize': 0}]
Hints
Hint 1
Use a data structure that preserves insertion order and supports efficient move-to-end operations
Hint 2
Convert unhashable types like dicts and lists into a hashable representation by recursively encoding their structure
Hint 3
When normalizing dict keys, sort the key-value pairs to ensure consistent hashing regardless of insertion order
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The solution maintains an LRU cache using Python's OrderedDict, which preserves insertion order and provides O(1) access, insertion, and deletion. The key insight is handling composite, unhashable keys by converting them into hashable representations.
Key Normalization:
Create a recursive _freeze function that converts any structure into a hashable tuple:
- Primitives remain unchanged
- Lists become
("list", tuple_of_frozen_elements) - Tuples become
("tuple", tuple_of_frozen_elements) - Sets become
("set", sorted_tuple_of_frozen_elements)— sorting ensures consistent ordering - Dicts become
("dict", sorted_tuple_of_frozen_pairs)— sorting by repr ensures equivalent dicts hash identically
Type tags prevent collisions between different structures containing the same data (e.g., [1, 2] vs (1, 2)).
LRU Tracking:
The OrderedDict stores entries in order from least to most recently used:
- On cache hit: remove the entry and reinsert it at the end via
pop+ reassignment - On cache miss with
maxsize > 0: add the new entry; if over capacity, remove the first (oldest) entry withpopitem(last=False) - Each
getincrements either hits or misses clearresets the cache and counterscache_inforeports current state
Why It Works:
The ordering invariant is maintained because every access moves the key to the end, and eviction always removes from the front. The front entry is always the least recently used. Frozen keys ensure that {"a": 1, "b": 2} and {"b": 2, "a": 1} map to the same cache slot.
Complexity
- Time: O(1) per
getorclearoperation (amortized for OrderedDict), O(K log K) for key normalization where K is the size of the key structure due to sorting sets and dicts - Space: O(maxsize × average_entry_size) for the cache storage
Solution
from collections import OrderedDict
from typing import List
def _freeze(value):
"""Convert unhashable structures to hashable tuples with type tags."""
if isinstance(value, dict):
items = [(_freeze(k), _freeze(v)) for k, v in value.items()]
return ("dict", tuple(sorted(items, key=repr)))
if isinstance(value, list):
return ("list", tuple(_freeze(item) for item in value))
if isinstance(value, tuple):
return ("tuple", tuple(_freeze(item) for item in value))
if isinstance(value, set):
return ("set", tuple(sorted((_freeze(item) for item in value), key=repr)))
return (type(value).__name__, value)
def simulate_lru_cache(maxsize, operations, arguments):
cache = OrderedDict()
results = []
hits = misses = 0
for operation, args in zip(operations, arguments):
if operation == "get":
key = _freeze(args[0])
if key in cache:
hits += 1
value = cache.pop(key)
cache[key] = value
results.append(value)
else:
misses += 1
value = args[1]
if maxsize > 0:
cache[key] = value
if len(cache) > maxsize:
cache.popitem(last=False)
results.append(value)
elif operation == "clear":
cache.clear()
hits = misses = 0
results.append(None)
elif operation == "cache_info":
results.append({
"hits": hits,
"misses": misses,
"maxsize": maxsize,
"currsize": len(cache)
})
return results