Peak Active Couriers: Sweep-Line with Per-Worker Deduplication
Greedy & IntervalsModel answerLast updated
Given delivery records with overlapping intervals per courier, find the maximum number of distinct couriers working simultaneously using a sweep-line algorithm.
Peak Active Couriers
A logistics platform tracks courier activity as a list of delivery records. Each record is a tuple (courier_id, start_time, end_time) where both times are integers and end_time is exclusive — a courier holding interval [s, e) is active at every moment t where s <= t < e.
A courier may accept several deliveries at once. That means one courier can appear in multiple overlapping records. For the purposes of this problem, a courier counts as one active courier regardless of how many deliveries they are simultaneously handling.
What you need to do
Part a) Write a function that returns the maximum number of distinct couriers active at any single moment in time.
Part b) Design and implement an O(n log n) sweep-line solution. As part of your answer:
- Explain how you construct events from the input records.
- Explain how you avoid counting the same courier twice when they hold multiple overlapping deliveries.
- Explain how ties at the same timestamp should be broken so that a record ending at time
tdoes not overlap a record starting at timet.
Part c) Suppose a teammate writes sorting key (courier_id, time, delta) for the event tuples. Explain precisely why this is wrong, give a concrete counter-example, and provide the correct sort key with justification.
Part d) How would the solution change if you instead wanted the peak number of concurrent deliveries (not distinct couriers)? What simplification becomes possible?
Function signature
def peak_active_couriers(records: list[tuple[int, int, int]]) -> int:
...
Examples
records = [(1, 1, 5), (2, 2, 6)]
# Courier 1 active [1,5), Courier 2 active [2,6)
# During [2,5) both are active → peak = 2
peak_active_couriers(records) == 2
records = [(1, 1, 5), (1, 3, 8)]
# Same courier holds two overlapping deliveries
# Only 1 distinct courier at any moment → peak = 1
peak_active_couriers(records) == 1
records = [(1, 1, 3), (2, 3, 5)]
# Record 1 ends at 3, record 2 starts at 3 — exclusive end means no overlap
peak_active_couriers(records) == 1
Constraints
0 <= len(records) <= 10^5- All times are integers (may be negative or very large; only relative order matters).
- Records with
start_time >= end_timerepresent empty intervals and should be ignored. - Your solution must run in O(n log n) time and O(n) space.
What a strong answer covers
- Correct deduplication logic and why a simple boolean flag fails.
- The exact sort key and why primary sorting on anything other than time breaks the sweep.
- Complexity analysis for both the deduplicated and non-deduplicated variants.
- Edge cases: empty input, zero-length intervals, a single courier with many nested deliveries, back-to-back intervals for the same courier.
Hints
Hint 1
Turn each record into two timestamped events: one for when the courier becomes (potentially) active and one for when they become (potentially) inactive. Then process events in time order — this is the core sweep-line idea.
Hint 2
A boolean 'is this courier active?' flag breaks when a courier holds nested or overlapping deliveries. Think about what additional per-courier state lets you correctly delay the 'courier goes idle' transition until all their open deliveries are closed.
Hint 3
When two events share the same timestamp, the type of event matters for correctness. Ask yourself: should a delivery ending at time t and one starting at time t be considered overlapping? Use that answer to decide which event type must be processed first, and encode that ordering into your sort key.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a variant of the classic "maximum overlapping intervals" sweep. The twist is that we count distinct couriers, not individual delivery records, so we need per-courier deduplication.
Building and sorting events
Convert each record (courier_id, s, e) into two events:
(s, +1, courier_id)— a delivery for this courier opens(e, -1, courier_id)— a delivery for this courier closes
Skip any record where s >= e (empty interval).
Sort events by (time, delta, courier_id). Because -1 < +1, this guarantees that close events at time t are processed before open events at time t. That is exactly the exclusive-end semantics: a delivery ending at 5 and one starting at 5 do not overlap, and processing the close first keeps the count correct.
Deduplication with a per-courier open-order counter
Keep a dictionary open_count[c] tracking how many deliveries courier c currently has open. Walk the sorted events:
- On
+1: incrementopen_count[c]. If it transitions0 → 1, the courier just became active, so increment the globalactivecounter and update the running peak. - On
-1: decrementopen_count[c]. If it transitions1 → 0, the courier is now fully free, so decrementactive.
The counter is the key insight. A plain boolean fails on nested intervals: if courier 1 holds [1, 10) and [2, 4), the close event at t=4 would clear the flag even though the courier is still working until t=10. The counter defers the "goes idle" signal until the last open delivery closes.
Only an open event can raise the peak, so we update best only after processing a +1.
Part (c): why (courier_id, time, delta) is wrong
If courier_id is the primary sort key, the events are grouped by courier instead of by time. The sweep processes all of courier A's history, then all of courier B's, and so on. The global counter never sees two couriers simultaneously, so the peak is always at most 1.
Concrete counter-example:
records = [(1, 1, 5), (2, 2, 6)]
Sorted by (courier_id, time, delta):
(1, +1)@1, (1, -1)@5, (2, +1)@2, (2, -1)@6
Time jumps backwards from 5 to 2 between the two couriers. The counter reaches 1 during courier 1's window, drops to 0, then reaches 1 again during courier 2's window. Computed peak: 1. True peak: 2.
Correct key: (time, delta, courier_id).
timemust be primary — a sweep is meaningless unless events are in chronological order.deltais secondary, with-1before+1— enforces exclusive-end semantics.courier_idis only a deterministic tiebreaker for stability; correctness does not depend on it.
Python solution
from collections import defaultdict
def peak_active_couriers(records: list[tuple[int, int, int]]) -> int:
"""Return the max number of distinct couriers active at any instant.
Each record is (courier_id, start, end) with end exclusive."""
events = []
for courier_id, start, end in records:
if start >= end: # empty or inverted interval: skip
continue
events.append((start, 1, courier_id))
events.append((end, -1, courier_id))
# (time, delta, courier_id): ends (-1) before starts (+1) at the same time
events.sort()
open_count = defaultdict(int)
active = best = 0
for _, delta, courier_id in events:
if delta == 1:
open_count[courier_id] += 1
if open_count[courier_id] == 1: # courier just became active
active += 1
best = max(best, active)
else:
open_count[courier_id] -= 1
if open_count[courier_id] == 0: # courier is now fully free
active -= 1
return best
Edge cases
| Case | Behaviour |
|---|---|
| Empty input | events is empty; returns 0. |
start >= end | Record is skipped; no events emitted. |
| Same courier, nested deliveries | Counter prevents double-counting and premature idle. |
Back-to-back intervals [1,3), [3,5) for one courier | Courier dips idle at 3, active count briefly drops then rises; peak unaffected. |
| Duplicate identical records for one courier | Counter goes to 2 on the second open; the courier still counts as 1. |
| All couriers overlap perfectly | Peak equals the number of distinct couriers. |
Part (d): peak concurrent deliveries
If you want the peak number of open delivery records rather than distinct couriers, per-courier tracking is unnecessary. Every event directly adjusts a single global counter:
def peak_concurrent_deliveries(records: list[tuple[int, int, int]]) -> int:
events = []
for _, start, end in records:
if start < end:
events.append((start, 1))
events.append((end, -1))
events.sort() # (-1) still sorts before (+1) at equal times
current = best = 0
for _, delta in events:
current += delta
best = max(best, current)
return best
courier_id is dropped entirely. The rest of the structure is identical.
An alternative is the two-pointer approach: sort starts and ends into separate arrays, then scan starts while popping ends that close at or before the current start. Same O(n log n) complexity, avoids building tuples.
Complexity
| Time | Space | |
|---|---|---|
| Distinct-courier version | O(n log n) — sort dominates | O(n) events + O(D) courier map, D ≤ n |
| Concurrent-deliveries version | O(n log n) | O(n) events only |
The sweep itself is O(n) in both cases; sorting 2n events is the bottleneck.