Multiset Frequency Log with Lazy Snapshot Pool Top-K
Data Structure DesignAuto-graded · 23 test casesLast updated
Simulate insert, remove and top-k queries on a multiset using a snapshot pool whose stale entries are discarded lazily, testing hash maps with heaps and exact rule-following.
You are given a log of operations to run, in order, against an initially empty multiset of integers. Return the result of every operation.
The topK operation is defined through an explicit snapshot pool. Follow the rules below literally, including the note about repeated values. The expected outputs depend on every rule.
State
count[v]: the number of copies ofvcurrently in the multiset. A value that is not present has count0.- A snapshot pool: a collection of pairs
(f, v)(a frequency and a value). The same pair may appear in the pool several times, and each copy is tracked separately. The pool starts empty.
Operations
Operation i is operations[i] and takes its parameter from arguments[i], a list with exactly one integer.
"insert" with [x]
- Increase
count[x]by 1. - Add one copy of the snapshot
(count[x], x)to the pool, using the new count. - The result is
None.
"remove" with [x]
- If
count[x] == 0, do nothing. Do not touch the pool. - Otherwise decrease
count[x]by 1. - If the new
count[x]is at least 1, add one copy of the snapshot(count[x], x)to the pool. If the new count is 0, add nothing to the pool. - The result is
Nonein every case.
"topK" with [k]
Let limit = max(0, k). Start with an empty answer list and examine pool snapshots one at a time in this order:
- higher
ffirst; - among equal
f, smallervfirst; - identical pairs are interchangeable.
Repeat the following until the answer has limit entries (this is checked before examining each snapshot) or no unexamined snapshots remain:
- Take the next snapshot
(f, v)in that order. - If
f == count[v](the snapshot is valid), appendvto the answer and keep that snapshot in the pool. - Otherwise (the snapshot is stale), remove that copy from the pool permanently.
Snapshots that were never examined stay in the pool unchanged. The multiset counts are not modified by topK. The result is the answer list.
Important notes on the rules
- Each valid snapshot adds its value to the answer, and the same pair can be in the pool more than once. So a value can appear more than once in a
topKresult. For example,insert(x), insert(x), remove(x)leaves two copies of(1, x)in the pool, and both are valid whilecount[x] == 1. This is intended, and the answer must includexonce per valid copy that is examined. - A stale snapshot that was not examined stays in the pool. If its value's count later returns to the snapshot's frequency, it becomes valid again, in addition to any copy added by the operation that restored that count.
- If
limit == 0or the pool is empty, the result is[]. No snapshots are examined whenlimit == 0. - A removal that brings a count to 0 adds no snapshot. All existing snapshots of that value are then stale because every snapshot frequency is at least 1.
Output
Return a list with one entry per operation, in input order: None for insert and remove, and the answer list for topK.
Constraints
len(operations) == len(arguments), up to about10^5.- Every operation name is
"insert","remove"or"topK". - Every
arguments[i]contains exactly one integer. - Inserted and removed values are integers and may be negative.
kis an integer and may be zero, negative, or larger than the pool can supply.- Aim for fast updates and queries. Rescanning or fully re-sorting everything on every operation will be too slow on large inputs.
Examples
Example 1
Input: process_frequency_queries(['insert', 'insert', 'insert', 'insert', 'insert', 'topK', 'remove', 'topK'], [[5], [5], [2], [2], [3], [2], [5], [3]])
Output: [None, None, None, None, None, [2, 5], None, [2, 3, 5]]
Example 2
Input: process_frequency_queries(['topK', 'insert', 'topK', 'remove', 'topK'], [[3], [7], [3], [7], [1]])
Output: [[], None, [7], None, []]
Example 3
Input: process_frequency_queries(['insert', 'insert', 'insert', 'topK', 'remove', 'remove', 'topK'], [[-1], [4], [-1], [5], [-1], [-1], [5]])
Output: [None, None, None, [-1, 4], None, None, [4]]
Hints
Hint 1
Keep a dictionary from value to its current count, and a heap that stores the snapshot pairs as (-frequency, value) so the heap order matches the required scan order.
Hint 2
Pushing one entry per rule is enough: push on insert, and on remove only when the new count is positive. Never modify or delete old entries outside of a query.
Hint 3
In a query, pop entries while the answer is shorter than max(0, k). Keep valid ones (frequency equals the current count) in both the answer and a side list, drop stale ones, then push the side list back into the heap.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The statement describes a snapshot pool. The natural way to implement it is a dictionary plus a heap.
- A dictionary
countsmaps each value to its current frequency. Every insert or remove updates it in O(1). When a count reaches zero, the key is deleted, which is equivalent to a count of 0. - A min-heap holds the pool as
(-frequency, value)pairs. Python's heap is a min-heap, so the pair with the highest frequency comes out first, and ties go to the smaller value. This is exactly the scan order in the statement.
Updates follow the rules directly. insert pushes the new snapshot. remove pushes a snapshot only if the new count is still positive. Nothing is ever edited or deleted inside the heap during updates.
For topK(k), pop snapshots while the answer has fewer than max(0, k) entries and the heap is not empty:
- If
counts.get(value, 0)equals the snapshot's frequency, the snapshot is valid. Append the value to the answer and remember the snapshot. - Otherwise it is stale and is dropped for good.
Afterwards, push the remembered valid snapshots back so the pool is restored. Snapshots that were never popped are untouched, as the rules require.
Why it matches the rules
- The heap order is the required scan order, so popping examines snapshots in the specified sequence.
- The loop condition is checked before each pop, so no snapshot is examined after the answer is full. Unexamined stale snapshots therefore remain in the pool and may later become valid again.
- Identical valid snapshots are each added to the answer, which is why a value can appear more than once. This duplicate behavior is part of the defined task, so the code does not deduplicate.
- Dropping a stale snapshot is final, as the rules state, and valid ones are returned to the pool.
Complexity
Let H be the heap size and s the number of stale snapshots dropped during a query.
insertandremove: O(log H) each.topK(k): O((k + s) log H). Each stale snapshot is dropped only once, so the stale cost amortizes to O(log H) per update.- Space: O(D + H), where
Dis the number of distinct live values. In the worst caseHgrows with the number of updates.
Reference solution
import heapq
from typing import List, Optional
def process_frequency_queries(operations: List[str], arguments: List[List[int]]) -> List[Optional[List[int]]]:
counts = {}
heap = []
results = []
for operation, args in zip(operations, arguments):
if operation == "insert":
value = args[0]
counts[value] = counts.get(value, 0) + 1
heapq.heappush(heap, (-counts[value], value))
results.append(None)
elif operation == "remove":
value = args[0]
if counts.get(value, 0) > 0:
counts[value] -= 1
if counts[value] == 0:
del counts[value]
else:
heapq.heappush(heap, (-counts[value], value))
results.append(None)
elif operation == "topK":
k = args[0]
selected = []
answer = []
while heap and len(answer) < max(0, k):
entry = heapq.heappop(heap)
neg_frequency, value = entry
if counts.get(value, 0) == -neg_frequency:
selected.append(entry)
answer.append(value)
for entry in selected:
heapq.heappush(heap, entry)
results.append(answer)
else:
raise ValueError("unknown operation")
return results