Simulate a Frequency-Eviction Cache (LFU Cache)
Data Structure DesignAuto-graded · 15 test casesLast updated
Tests ability to simulate a Least-Frequently-Used cache by processing a sequence of get/put operations and returning the complete history of return values.
Frequency-Eviction Cache Simulator
You are building a cache that evicts the least-frequently-used entry when it is full and a new key must be inserted.
Cache Rules
-
put(key, value)— Insert or update the entry forkey.- If
keyalready exists, update its value and increment its access frequency. - If
keydoes not exist and the cache is not full, insert it with frequency 1. - If
keydoes not exist and the cache is full, first evict the entry with the lowest frequency. Ties in frequency are broken by evicting the least-recently-used (i.e., the entry whose last access time is the oldest). Then insert the new entry with frequency 1. putalways returnsNone(represented as-1in the output list).
- If
-
get(key)— Retrieve the value forkey.- If
keyexists in the cache, return its value and increment its access frequency. - If
keydoes not exist, return-1.
- If
Access time
Every get and put operation advances a global logical clock by 1, starting from 0. The operation at index i in the list has timestamp i. This timestamp is used to break eviction ties.
Your task
Implement the function simulate_lfu_cache which accepts:
capacity— maximum number of entries the cache can hold (always ≥ 1).operations— a list of[op, key]or[op, key, value]entries whereopis either"get"or"put".
Return a list of integers: the return value of each operation in order. put operations always contribute -1 to the output.
Constraints
1 ≤ capacity ≤ 5001 ≤ len(operations) ≤ 2000- Each operation is
["get", key]or["put", key, value] 0 ≤ key ≤ 10000 ≤ value ≤ 10000- An operation list may contain only
gets, onlyputs, or any mix. - If a key is evicted and later re-inserted, its frequency resets to 1.
Examples
Example 1
Input: simulate_lfu_cache(2, [['put', 1, 10], ['put', 2, 20], ['get', 1], ['put', 3, 30], ['get', 2], ['get', 3]])
Output: [-1, -1, 10, -1, -1, 30]
Example 2
Input: simulate_lfu_cache(1, [['put', 5, 100], ['get', 5], ['put', 6, 200], ['get', 5], ['get', 6]])
Output: [-1, 100, -1, -1, 200]
Example 3
Input: simulate_lfu_cache(3, [['put', 1, 1], ['put', 2, 2], ['put', 3, 3], ['get', 1], ['get', 1], ['put', 4, 4], ['get', 2], ['get', 3], ['get', 4]])
Output: [-1, -1, -1, 1, 1, -1, -1, 3, 4]
Hints
Hint 1
Track each cached entry's frequency and last-access timestamp separately — a dict keyed by cache key works well.
Hint 2
For eviction, you need the entry with the minimum frequency; among ties, the one with the smallest timestamp. A simple linear scan over the cache entries is O(capacity) per eviction and is fast enough given the constraints.
Hint 3
Remember that both get and put count as accesses: after a put on an existing key, increment frequency and update the timestamp, just as you would for a get.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Data Structure
A single dictionary cache maps each key to a mutable list [value, frequency, last_access_time]. This gives O(1) lookup and update.
Operations
get(key)
- If the key is present: increment its frequency, update its timestamp, return its value.
- Otherwise: return
-1.
put(key, value)
- If the key is already present: update the value, increment frequency, update the timestamp (same semantics as
get+ value write). - If the key is absent and the cache is full: scan all cached entries to find the one with the minimum
(frequency, last_access_time)pair, evict it, then insert the new entry with frequency 1 and the current timestamp. - If the key is absent and the cache is not full: insert directly.
- Always append
-1to the result list.
Correctness
Using min(..., key=lambda k: (cache[k][1], cache[k][2])) resolves ties deterministically: lowest frequency wins, and within equal frequencies the entry with the older timestamp (smaller index) is evicted first — which is precisely the LRU tie-break rule.
Every operation increments the logical clock (via enumerate), so timestamps are unique and ties are always resolved unambiguously.
Complexity
- Time: O(N · C) where N = number of operations and C = capacity. Each eviction is an O(C) linear scan; all other operations are O(1).
- Space: O(C) for the cache dictionary, O(N) for the results list.
Given the constraints (N ≤ 2000, C ≤ 500), this is well within acceptable limits.
from typing import List
def simulate_lfu_cache(capacity: int, operations: list) -> list:
# cache[key] = [value, frequency, last_access_time]
cache = {}
results = []
for time, op in enumerate(operations):
if op[0] == "get":
key = op[1]
if key in cache:
cache[key][1] += 1
cache[key][2] = time
results.append(cache[key][0])
else:
results.append(-1)
else: # "put"
key, value = op[1], op[2]
if key in cache:
# Update existing entry
cache[key][0] = value
cache[key][1] += 1
cache[key][2] = time
else:
# Evict if at capacity
if len(cache) == capacity:
evict_key = min(
cache,
key=lambda k: (cache[k][1], cache[k][2])
)
del cache[evict_key]
# Insert new entry with freq=1
cache[key] = [value, 1, time]
results.append(-1)
return results