Simulate a Bounded LRU Cache with Hit/Miss Tracking
Data Structure DesignAuto-graded · 15 test casesLast updated
Tests ability to simulate a sequence of GET/PUT operations on a capacity-bounded LRU cache and return accumulated hit/miss statistics.
Bounded LRU Cache Simulation
You are given a cache capacity and a list of operations to perform on an LRU (Least Recently Used) cache. Simulate the cache and return statistics about the run.
How the cache works
- The cache holds at most
capacitykey-value pairs (both keys and values are non-negative integers). - PUT
(key, value): Insert or update the entry forkey.- If
keyalready exists, update its value and mark it as most recently used. - If
keydoes not exist and the cache is full, evict the least recently used entry first, then insert the new one.
- If
- GET
(key): Look upkey.- If found, mark it as most recently used and count it as a hit.
- If not found, count it as a miss. The cache is unchanged.
Your task
Given capacity and operations, simulate all operations in order and return a dict with exactly three keys:
| Key | Value |
|---|---|
"hits" | total number of GET hits |
"misses" | total number of GET misses |
"final_cache" | the contents of the cache after all operations, as a plain dict mapping each present key to its current value (order does not matter) |
Input format
operations is a list of [op, key, value] triples where:
opis either"GET"or"PUT"keyandvalueare non-negative integers- For
"GET"operations,valueis always0(ignore it)
Constraints
1 <= capacity <= 1001 <= len(operations) <= 20000 <= key <= 10000 <= value <= 10000- Every operation has
opequal to"GET"or"PUT" - The cache starts empty.
Examples
Example 1
Input: simulate_lru_cache(2, [['PUT', 1, 10], ['PUT', 2, 20], ['GET', 1, 0], ['PUT', 3, 30], ['GET', 2, 0], ['GET', 1, 0]])
Output: {'hits': 2, 'misses': 1, 'final_cache': {'1': 10, '3': 30}}
Example 2
Input: simulate_lru_cache(3, [['PUT', 5, 50], ['GET', 5, 0], ['GET', 9, 0], ['PUT', 6, 60], ['PUT', 7, 70], ['PUT', 8, 80], ['GET', 5, 0], ['GET', 6, 0]])
Output: {'hits': 2, 'misses': 2, 'final_cache': {'6': 60, '7': 70, '8': 80}}
Example 3
Input: simulate_lru_cache(1, [['PUT', 1, 100], ['GET', 1, 0], ['PUT', 2, 200], ['GET', 1, 0], ['GET', 2, 0]])
Output: {'hits': 2, 'misses': 1, 'final_cache': {'2': 200}}
Hints
Hint 1
Use an OrderedDict from Python's collections module to track insertion/access order efficiently.
Hint 2
On every successful GET and every PUT (insert or update), move that key to the 'most recently used' end of the OrderedDict.
Hint 3
For the final_cache value, simply convert the OrderedDict to a plain dict before returning.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is that an LRU cache requires two behaviors:
- O(1) key lookup — use a hash map.
- O(1) eviction of the least recently used entry — maintain access order.
Python's collections.OrderedDict provides both: it is a hash map that remembers insertion/update order, and supports move_to_end(key) in O(1) and popitem(last=False) to remove the oldest entry in O(1).
Algorithm
Maintain an OrderedDict where the front (oldest end) is the LRU entry and the back (newest end) is the MRU entry.
PUT(key, value):
- If
keyis already present, move it to the back (MRU) and update its value. - If
keyis new and the cache is full, pop from the front (LRU eviction), then insert at the back. - If
keyis new and there is room, just insert at the back.
GET(key):
- If
keyis present: incrementhits, move it to the back. - If
keyis absent: incrementmisses, do nothing.
After all operations, return hits, misses, and dict(cache).
Correctness
Every access (GET hit or PUT) marks the key as most recently used by moving it to the back. The front is always the least recently used, so popitem(last=False) is the correct eviction policy.
Complexity
- Time: O(n) for n operations — each operation is O(1) with
OrderedDict. - Space: O(capacity) for the cache.
from collections import OrderedDict
def simulate_lru_cache(capacity: int, operations: list) -> dict:
cache = OrderedDict()
hits = 0
misses = 0
for op, key, value in operations:
if op == "GET":
if key in cache:
hits += 1
cache.move_to_end(key)
else:
misses += 1
elif op == "PUT":
if key in cache:
cache.move_to_end(key)
else:
if len(cache) >= capacity:
cache.popitem(last=False) # evict LRU (front)
cache[key] = value
return {
"hits": hits,
"misses": misses,
"final_cache": dict(cache),
}