Parcel Runner Payout Ledger with Peak Overlap Queries
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a stateful ledger driven by operation lists: track per-runner payout sums and compute maximum simultaneous half-open intervals clipped to a query window.
Parcel Runner Payout Ledger
A dispatch service keeps a ledger of parcel runs. Every run is carried out by one runner during a half-open time span [start, end): the runner is busy from start up to, but not including, end. Each run pays a fixed amount.
You are given a script of ledger operations and must simulate a fresh, empty ledger processing them in order. The function receives two parallel lists:
operations: a list of operation names.arguments: a list wherearguments[i]is the list of arguments foroperations[i].
Three operations exist:
"record_delivery"with arguments[runner_id, start, end, pay]: add a run forrunner_idover[start, end)that payspay. ProducesNone."get_courier_total"with arguments[runner_id]: produces the sum ofpayover all runs recorded so far for that runner, or0if the runner has none."get_peak_concurrent"with arguments[window_start, window_end]: considers all runs recorded so far, restricted to the window[window_start, window_end). Produces the largest number of runs that are simultaneously active at one single instanttwithwindow_start <= t < window_end.
Details:
- A run is active at instant
twhenstart <= t < end. Because spans are half-open, a run ending at timexand another starting atxdo not overlap. - Every run counts individually, even when several belong to the same runner or have identical spans.
- If no run is active at any instant of the window, the peak is
0.
Return a list with one entry per operation, in order: None for record_delivery, and the integer result for the two query operations.
Constraints
0 <= start < end <= 10^90 <= window_start < window_end <= 10^91 <= pay <= 10^5runner_idconsists of lowercase letters and digits, length 1 to 30.- At most
2,000operations in total arerecord_deliveryorget_peak_concurrent. - At most
10,000operations areget_courier_total. operationsandargumentshave equal length.
Examples
Example 1
Input: run_parcel_ledger(['record_delivery', 'record_delivery', 'record_delivery', 'get_courier_total', 'get_courier_total', 'get_peak_concurrent', 'get_peak_concurrent', 'get_peak_concurrent'], [['c1', 10, 30, 25], ['c2', 20, 50, 40], ['c1', 40, 60, 30], ['c1'], ['c3'], [15, 45], [30, 40], [70, 100]])
Output: [None, None, None, 55, 0, 2, 1, 0]
Example 2
Input: run_parcel_ledger(['record_delivery', 'record_delivery', 'get_peak_concurrent'], [['c1', 10, 20, 15], ['c2', 20, 30, 15], [0, 50]])
Output: [None, None, 1]
Hints
Hint 1
Handle the totals and the overlap queries separately: a dictionary from runner to running sum answers totals in constant time.
Hint 2
For the peak query, first clip each run to the window using max of starts and min of ends, and ignore runs whose clipped span is empty.
Hint 3
Turn each clipped span into a +1 event at its start and a -1 event at its end, sort, and sweep. Apply all events sharing a timestamp before updating the maximum so touching spans do not count as overlapping.
Hint 4
Timestamps reach 10^9, so do not allocate an array indexed by time; only work with actual endpoints.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The ledger has two independent responsibilities, so handle them separately.
Totals. Keep a dictionary mapping each runner to the sum of their pay. record_delivery adds to it, and get_courier_total looks the runner up, defaulting to 0. Both are O(1), which matters with up to 10,000 total queries.
Peak overlap. Store every run as a (start, end) pair. For each peak query:
- Clip each run to the window:
s = max(start, window_start),e = min(end, window_end). - If
s >= e, the run is never active inside the window, so skip it. - Otherwise emit a
+1event atsand a-1event ate. - Sort the events by time. Walk through them, grouping all events with the same timestamp, add the group's net change to a running count, then update the maximum.
Why it is correct
A run is active at instant t in the window exactly when t lies in [max(start, window_start), min(end, window_end)), so clipping preserves precisely the part of each run that matters, and an empty clipped span can be dropped.
Between two consecutive distinct event times the set of active runs is constant. After applying every event at time T, the running count equals the number of clipped spans with s <= T < e, which is the concurrency on [T, next event). Checking the count after each timestamp group therefore sees every distinct concurrency level.
Applying all events at the same timestamp together implements the half-open rule: a run ending at x and another starting at x net to zero at x, so they are never counted together. With no overlapping runs there are no events and the peak stays 0. Runs from the same runner or with identical spans each add their own +1, as required.
Timestamps go up to 10^9, so the sweep uses only actual endpoints rather than an array over time.
Complexity
With n runs recorded so far:
record_delivery: O(1) time and space.get_courier_total: O(1) average.get_peak_concurrent: O(n log n) time, O(n) space for events.
At most about 1,000 queries over 1,000 runs gives roughly 2 * 10^7 basic steps, which is comfortably fast.
Reference solution
from typing import List, Optional
def run_parcel_ledger(operations: List[str], arguments: List[List]) -> List[Optional[int]]:
totals = {}
runs = []
results = []
for operation, args in zip(operations, arguments):
if operation == "record_delivery":
runner_id, start, end, pay = args
totals[runner_id] = totals.get(runner_id, 0) + pay
runs.append((start, end))
results.append(None)
elif operation == "get_courier_total":
results.append(totals.get(args[0], 0))
elif operation == "get_peak_concurrent":
window_start, window_end = args
events = []
for start, end in runs:
s = max(start, window_start)
e = min(end, window_end)
if s < e:
events.append((s, 1))
events.append((e, -1))
events.sort()
active = peak = 0
i = 0
while i < len(events):
t = events[i][0]
change = 0
while i < len(events) and events[i][0] == t:
change += events[i][1]
i += 1
active += change
if active > peak:
peak = active
results.append(peak)
else:
raise ValueError("Unknown operation")
return results