Batch Counter Updates with Global Shift and Min Extraction
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests lazy global offset propagation and min-heap with lazy deletion to efficiently manage counters under bulk increments and minimum extraction.
Problem Statement
You are building a lightweight task-tracking system for a fleet of workers. Each worker is identified by a unique integer ID and starts with a workload count of zero. Your system must process a sequence of operations in order:
"increment": Given a worker ID and a value, add that value to the specified worker's workload count."global_increment": Given a value, add it to every currently active worker's workload count simultaneously."pop_min": Find and permanently remove the active worker with the lowest workload count, then return that worker's ID. If two or more workers share the lowest count, remove and return the one with the smallest ID.
Operations that do not return a meaningful value (i.e., "increment" and "global_increment") contribute null to the output list.
Input Format
worker_ids: a list of distinct integers identifying the initial set of active workers.operations: a list of strings, each one of"increment","global_increment", or"pop_min".arguments: a parallel list of argument lists.- For
"increment":[worker_id, value] - For
"global_increment":[value] - For
"pop_min":[]
- For
Output Format
Return a list of the same length as operations. Each element is either:
Nonefor"increment"and"global_increment"operations, or- the integer ID of the removed worker for
"pop_min"operations.
Constraints
1 ≤ len(worker_ids) ≤ 10^51 ≤ len(operations) ≤ 10^5- All values passed to
"increment"and"global_increment"are non-negative integers. - Worker IDs are distinct positive integers.
"pop_min"will not be called more times than there are active workers.- A
"pop_min"on an empty set of workers should returnNone.
Examples
Example 1
Input: simulate_worker_queue([1, 2], ['increment', 'global_increment', 'pop_min', 'pop_min'], [[1, 10], [5], [], []])
Output: [None, None, 2, 1]
Example 2
Input: simulate_worker_queue([3, 1, 2], ['global_increment', 'increment', 'increment', 'pop_min', 'pop_min', 'pop_min'], [[7], [3, 2], [1, 2], [], [], []])
Output: [None, None, None, 2, 1, 3]
Example 3
Input: simulate_worker_queue([1, 2, 3], ['increment', 'increment', 'global_increment', 'pop_min', 'increment', 'pop_min', 'pop_min'], [[1, 4], [2, 4], [3], [], [1, 1], [], []])
Output: [None, None, None, 3, None, 2, 1]
Hints
Hint 1
A global increment shifts every active worker's count by the same amount — that means their relative order never changes. Can you track one shared offset instead of updating every worker individually?
Hint 2
Store each worker's count relative to the shared offset. True count = stored value + offset. A min-heap keyed on stored values still gives you the correct minimum because all live workers share the same offset.
Hint 3
Python's heapq has no update operation. When a worker's stored value changes, push a new entry and leave the old one. On pop_min, discard any entry whose stored value no longer matches what the worker currently holds — that entry is stale.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge
A naive implementation loops over every worker on each "global_increment", costing O(N) per call. With up to 10^5 workers and 10^5 operations that is O(N·M) in the worst case — far too slow.
Two standard tricks, combined, reduce every operation to O(log N) amortised.
Trick 1 — shared global offset (lazy propagation)
Instead of updating every worker's count when a global increment arrives, maintain one integer global_offset equal to the running total of all global increments so far. For each worker store only a relative value so that:
true_count(worker) = stored[worker] + global_offset
"global_increment"(v)becomesglobal_offset += v— O(1)."increment"(w, v)becomesstored[w] += v.
Crucially, adding the same constant to every live worker does not change their relative order. The heap can therefore be keyed entirely on stored values; global_offset never needs to enter the heap.
Trick 2 — min-heap with lazy deletion
Python's heapq has no decrease-key or remove operation. The workaround: whenever a worker's stored value changes, push a new entry (stored[w], w) and leave the old entry in place. An entry is stale when:
- the worker has already been popped (its key is absent from
stored), or - the entry's value no longer matches
stored[worker](a later"increment"superseded it).
On "pop_min", repeatedly discard the heap's top entry if it is stale, then pop the first valid one. Because values only ever increase (all increments are non-negative), a stale entry for worker w always has a value ≤ the current stored value of w. It will never masquerade as a better candidate than the true minimum.
Tuple comparison (stored_value, worker_id) handles tie-breaking automatically: when two entries share the same stored value the smaller ID wins, which is exactly the required rule.
Why it is correct
- Invariant: for every live worker,
stored[w] + global_offsetequals its true count. Initialisation sets both to zero; each operation preserves this by construction. - Heap validity: every live worker always has at least one heap entry whose value matches
stored[w], so the true minimum is never missing from the heap. - Stale safety: stale entries have values ≤ the current stored value of their worker. They are detected immediately by the equality check and discarded before any result is produced.
Complexity
Let N = number of workers, M = number of operations, H = heap size ≤ N + M.
| Operation | Time |
|---|---|
| Initialisation | O(N) via heapify |
"increment" | O(log H) |
"global_increment" | O(1) |
"pop_min" | O(log H) amortised |
"pop_min" is amortised because each pushed entry is popped at most once over the lifetime of the structure. Overall space is O(N + M).
Edge cases
- Empty worker set / extra
"pop_min"calls: returnNone. incrementon an already-removed worker: the worker is absent fromstored, so the update is silently ignored.val = 0: valid; pushes a harmless duplicate that becomes stale once the worker is popped.- Tie-breaking: handled for free by tuple ordering — no extra code needed.
Reference solution
import heapq
from typing import List, Optional
def simulate_worker_queue(
worker_ids: List[int],
operations: List[str],
arguments: List[List[int]],
) -> List[Optional[int]]:
# stored[wid] holds each worker's count relative to global_offset.
# True count = stored[wid] + global_offset.
stored = {wid: 0 for wid in worker_ids}
# Min-heap of (stored_value, worker_id).
# Tuple ordering gives free tie-breaking by ID.
heap = [(0, wid) for wid in stored]
heapq.heapify(heap)
global_offset = 0 # cumulative total of all global_increment calls
result = []
for operation, args in zip(operations, arguments):
if operation == "increment":
wid, value = args
if wid in stored:
stored[wid] += value
heapq.heappush(heap, (stored[wid], wid))
result.append(None)
elif operation == "global_increment":
# Shift the shared baseline; no individual updates needed.
global_offset += args[0]
result.append(None)
elif operation == "pop_min":
# Discard stale entries: worker already removed OR value outdated.
while heap and heap[0][1] not in stored:
heapq.heappop(heap)
while heap and heap[0][0] != stored[heap[0][1]]:
heapq.heappop(heap)
if not heap:
result.append(None)
else:
_, wid = heapq.heappop(heap)
del stored[wid]
result.append(wid)
else:
raise ValueError(f"Unknown operation: {operation}")
return result