Simulate a Frequency-Based Eviction Cache
Data Structure DesignAuto-graded · 15 test casesLast updated
Tests ability to simulate a sequence of get/put/delete operations on an LFU-like cache that evicts the least-frequently-used key on overflow, with tie-breaking by insertion order.
Frequency-Based Eviction Cache
You are building a simple Frequency-Based Eviction Cache (FBEC). The cache has a fixed capacity and supports three operations: get, put, and delete.
Eviction Rule
Whenever a put would exceed the cache's capacity, exactly one existing entry is evicted before the new entry is inserted. The eviction target is chosen as follows:
- Among all current entries, find the one(s) with the lowest access frequency (number of times the key has been successfully retrieved via
get—putanddeletedo not count toward frequency). - If there is a tie in frequency, evict the key that was inserted earliest (i.e., the one whose most recent
puthas the smallest index among tied keys, counting only successful insertions).
Operations
Each operation is a list of two or three elements:
| Format | Meaning |
|---|---|
["get", key] | Return the value associated with key. If the key is not present, return -1. A successful get (key found) increments that key's frequency by 1. |
["put", key, value] | Insert or update key → value. If key already exists, update its value without changing its frequency or insertion-order rank. If key is new and the cache is at capacity, evict one entry first (see rule above), then insert the new key with frequency 0 and the current insertion rank. |
["delete", key] | Remove key from the cache. If the key is not present, this is a no-op. |
Task
Given the cache capacity and a list of operations, simulate the cache and return a list containing the result of every get operation, in order.
Constraints
1 ≤ capacity ≤ 5001 ≤ len(operations) ≤ 2000- Each operation is
["get", key],["put", key, value], or["delete", key] keyis always a non-empty string;valueis always an integer- The cache starts empty
- A
putfor a key that already exists (update) does not trigger eviction even if the cache is at capacity - After eviction, the newly inserted key has frequency 0 and takes the next insertion rank
Examples
Example 1
Input: simulate_fbec(2, [['put', 'a', 1], ['put', 'b', 2], ['get', 'a'], ['put', 'c', 3], ['get', 'b'], ['get', 'a'], ['get', 'c']])
Output: [1, -1, 1, 3]
Example 2
Input: simulate_fbec(3, [['put', 'x', 10], ['put', 'y', 20], ['put', 'z', 30], ['get', 'x'], ['get', 'x'], ['get', 'y'], ['put', 'w', 40], ['get', 'z'], ['get', 'w']])
Output: [10, 10, 20, -1, 40]
Example 3
Input: simulate_fbec(1, [['put', 'm', 5], ['get', 'm'], ['put', 'n', 9], ['get', 'm'], ['get', 'n']])
Output: [5, -1, 9]
Hints
Hint 1
Track three things per cache entry: its value, its get-frequency, and a monotonically increasing insertion-rank (a counter you bump on every new/successful insert).
Hint 2
For eviction, scan all current entries and pick the one minimizing (frequency, insertion_rank) — Python's min() with a tuple key does this in one line.
Hint 3
An update put (key already exists) must not reset the frequency or the insertion rank — only the stored value changes.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The cache maps each key to three pieces of data: its stored value, its get-frequency, and an insertion rank. The rank is a global counter that starts at 0 and increments by 1 every time a new key is inserted (updates and gets leave it unchanged).
Per-operation logic
get key
- If the key is present, increment its frequency and record its value in the results list.
- If absent, record -1.
put key value
- If the key already exists, overwrite the value only — frequency and rank are untouched, and no eviction occurs.
- If the key is new:
- If
len(cache) >= capacity, evict the entry with the smallest(freq, rank)tuple (Python'sminwith a tuple key handles both criteria in one pass). - Insert the new key with
freq=0and the next insertion rank.
- If
delete key
- Remove the key if present; otherwise no-op.
Correctness
The tie-break "evict the key inserted earliest among those with minimum frequency" is modeled exactly by the rank counter: a lower rank means it was inserted earlier. Sorting on (freq, rank) therefore implements the stated eviction policy without ambiguity.
Updating an existing key (put when key is already in the cache) explicitly must not reset rank or frequency, which is enforced by the early-return branch.
Complexity
Let n = number of operations and C = capacity.
- Each
getanddeleteis O(1). - Each
putthat triggers eviction requires a linear scan over at most C entries: O(C). - Overall: O(n · C) time, O(C) space.
With the given constraints (n ≤ 2000, C ≤ 500) this is well within limits.
from typing import List
def simulate_fbec(capacity: int, operations: list) -> list:
# cache[key] = {"value": int, "freq": int, "rank": int}
cache = {}
insert_counter = 0 # monotonically increasing insertion rank
results = []
for op in operations:
cmd = op[0]
if cmd == "get":
key = op[1]
if key in cache:
cache[key]["freq"] += 1
results.append(cache[key]["value"])
else:
results.append(-1)
elif cmd == "put":
key = op[1]
value = op[2]
if key in cache:
# Update only the value; frequency and rank are preserved
cache[key]["value"] = value
else:
# Evict if at capacity
if len(cache) >= capacity:
evict_key = min(cache, key=lambda k: (cache[k]["freq"], cache[k]["rank"]))
del cache[evict_key]
# Insert new entry
cache[key] = {"value": value, "freq": 0, "rank": insert_counter}
insert_counter += 1
elif cmd == "delete":
key = op[1]
if key in cache:
del cache[key]
return results