Payroll From an Event Log With Surge Windows
Greedy & IntervalsModel answerLast updated
Turn a day's delivery events into total driver pay, then add doubled-rate surge windows by splitting intervals at boundaries, and decide how to handle messy or inconsistent logs.
A delivery platform records everything a driver does during one day as a list of JSON events. Each event has these fields:
order_id: identifies the deliveryevent_type: either"start"or"complete"timestamp: a numeric value in minutes (assume parsing and normalization are already done)base_rate_per_minute: the pay rate for that delivery
A delivery is paid for the time between its start event and its completion event:
pay = (complete_time - start_time) * base_rate_per_minute
Part 1. Write a function that returns the driver's total pay for the day, summed over all deliveries.
Part 2 (follow-up). Some time ranges are flagged as surge windows, during which the rate is doubled. If a delivery only partly overlaps a surge window, the delivery must be split at each window boundary, and the doubled rate applies only to the pieces that fall inside a window.
Part 3. Explain how your solution behaves with dirty data: missing events, duplicates, events that are out of order, and impossible orderings.
Things to address in your answer:
- The assumptions you would confirm before coding
- The algorithm and its time and space complexity
- How you treat overlapping surge windows, deliveries that touch a boundary exactly, and deliveries that run concurrently
- Working code
Hints
Hint 1
Do not trust the order of lines in the log. Group the events by `order_id` first, then decide what each group represents by looking at event types and timestamps.
Hint 2
Reduce every order to one clean triple (start, end, rate), or reject it with a recorded reason. This validation step is where all the malformed-input rules live, so keep it separate from the pay arithmetic.
Hint 3
For the surge follow-up, sort and merge the surge windows into disjoint ranges first, so overlapping windows cannot stack the multiplier. Then walk each delivery from left to right, emitting segments at each boundary, and use binary search to find the first window that matters.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Clarify the contract first
Before coding, I would state these assumptions:
- Event types are
startandcomplete. Timestamps are minutes. If they were seconds, I would convert once at the input boundary. - The rate is read from the start event. If the complete event also carries one, it must agree.
- Different orders may overlap in time because drivers can stack deliveries. Each order is paid on its own unless told otherwise.
- Surge windows are half-open ranges
[s, e). Overlapping windows still mean 2x, never 4x. - The output is the total plus a list of rejected orders with reasons. Silently discarding bad data hides payroll bugs.
- For real money, use integer cents or
Decimal, not floats.
Approach
- Group by
order_id. Sequence comes from timestamps, not from line order. - Validate each group and reduce it to
(start, end, rate), or reject it with a reason. - Part 1 pay is
(end - start) * rate, summed across valid orders. - Part 2: sort and merge the surge windows into disjoint ranges. For each order, find the first window that could intersect it by binary search on window starts. Then sweep a cursor from
starttoend, emitting a segment at every boundary: a normal segment (multiplier 1) up to the next window start, then a surge segment (multiplier 2) up tomin(window_end, end).
The split is mathematically the same as base_pay + rate * overlap_with_surges. I would still implement the explicit split, because it is what the question asks for and it generalizes to tiered multipliers such as 1.5x or 3x.
Why it is correct
- Validation guarantees one start, one completion and
start <= end, so each valid order yields exactly one interval. - After merging, windows are sorted and disjoint. The cursor moves strictly forward, and each segment either ends at a window start, at a window end, or at the order's end. The segments therefore tile
[start, end)with no gaps and no overlap. - A minute gets the 2x multiplier if and only if it lies inside a merged window, so overlapping window definitions cannot double-apply.
- With half-open ranges, an order that merely touches a window boundary gets zero overlap.
Malformed input policy
| Problem | Policy |
|---|---|
| Missing field, unknown event type, non-numeric timestamp or rate, negative rate | Reject the event and log the error |
| Exact duplicate (same type, timestamp, rate) | Collapse silently; retries and at-least-once delivery cause these |
| Conflicting duplicates (two different start times) | Reject the whole order as ambiguous rather than guess earliest or latest |
| Missing start or complete | Reject and flag for reconciliation (may be in progress or span midnight) |
| Complete before start | Reject as invalid ordering; equal timestamps yield zero pay |
| Rate differs between start and complete | Reject |
A lenient mode (earliest start, latest completion) is possible, but that is a product decision. For payroll I would fail loudly and route the case to manual review.
Code
from bisect import bisect_right
from collections import defaultdict
from numbers import Real
START, COMPLETE = "start", "complete"
SURGE_MULT = 2
def is_num(x):
return isinstance(x, Real) and not isinstance(x, bool)
def merge_windows(windows):
merged = []
for s, e in sorted(w for w in windows if w[0] < w[1]):
if merged and s <= merged[-1][1]:
merged[-1][1] = max(merged[-1][1], e)
else:
merged.append([s, e])
return [tuple(w) for w in merged]
def split_interval(start, end, wins, win_starts):
segs = []
i = max(bisect_right(win_starts, start) - 1, 0)
cur = start
while cur < end:
if i >= len(wins) or wins[i][0] >= end:
segs.append((cur, end, 1))
break
ws, we = wins[i]
if we <= cur: # window entirely behind the cursor
i += 1
continue
if cur < ws:
segs.append((cur, ws, 1))
cur = ws
seg_end = min(we, end)
segs.append((cur, seg_end, SURGE_MULT))
cur = seg_end
i += 1
return segs
def build_intervals(events, errors):
groups = defaultdict(set)
for ev in events:
oid = ev.get("order_id")
etype = ev.get("event_type")
ts = ev.get("timestamp")
rate = ev.get("base_rate_per_minute")
if oid is None:
errors.append((None, "missing order_id"))
continue
oid = str(oid)
if etype not in (START, COMPLETE):
errors.append((oid, f"unknown event_type {etype!r}"))
continue
if not is_num(ts):
errors.append((oid, "invalid timestamp"))
continue
if rate is not None and (not is_num(rate) or rate < 0):
errors.append((oid, "invalid rate"))
continue
groups[oid].add((etype, ts, rate))
out = {}
for oid, evs in groups.items():
starts = [e for e in evs if e[0] == START]
ends = [e for e in evs if e[0] == COMPLETE]
if not starts or not ends:
errors.append((oid, "missing start or complete"))
continue
if len({e[1] for e in starts}) > 1 or len({e[1] for e in ends}) > 1:
errors.append((oid, "conflicting duplicate events"))
continue
rates = {e[2] for e in starts}
if len(rates) != 1 or None in rates:
errors.append((oid, "missing or conflicting start rate"))
continue
rate = rates.pop()
end_rates = {e[2] for e in ends} - {None}
if end_rates and end_rates != {rate}:
errors.append((oid, "rate mismatch"))
continue
s, e = starts[0][1], ends[0][1]
if e < s:
errors.append((oid, "complete before start"))
continue
out[oid] = (s, e, rate)
return out
def daily_pay(events, surge_windows=()):
errors = []
intervals = build_intervals(events, errors)
wins = merge_windows(surge_windows)
starts = [w[0] for w in wins]
total = 0
per_order = {}
for oid, (s, e, r) in intervals.items():
pay = sum((b - a) * r * m for a, b, m in split_interval(s, e, wins, starts))
per_order[oid] = pay
total += pay
return total, per_order, errors
Complexity
Let N be the number of events, P the number of surge windows, M the number of valid orders and S the total segments produced.
- Grouping and validation: O(N)
- Merging windows: O(P log P)
- Splitting: O(log P) per order plus the windows it touches
- Total time: O(N + P log P + M log P + S); space: O(N + P)
Edge cases to test
- Empty log gives 0.
- Order fully inside, fully outside, or exactly touching a window.
- Order spanning several windows.
- Overlapping, adjacent or zero-length windows.
- Retried duplicate events.
- Order IDs that are ints in one event and strings in another (normalize with
str). - Zero-duration orders (pay 0).
Common mistakes
- Assuming the log is sorted.
- Letting overlapping windows stack to 4x.
- Using closed ranges and double-counting boundary points.
- Scanning every window for every order instead of using binary search.
- Silently dropping bad orders, so the total is wrong with no trace.
- Using floating point for currency.