Maintain Contiguous Delivery Sequence and Detect Gaps
Data Structure DesignAuto-graded · 14 test casesLast updated
Tests managing out-of-order arrivals with sets to track the longest complete prefix and identify missing elements in a sparse range.
Maintain Contiguous Delivery Sequence and Detect Gaps
You are implementing a DeliveryMonitor system that processes incoming shipment confirmations identified by non-negative integers. Confirmations arrive in any order and may be duplicated. Your system must answer two queries:
- Complete Sequence Endpoint: What is the largest value
ksuch that every integer from0throughkhas been confirmed? - Gap Detection: Which integers between
0and the highest confirmed value are still missing?
Operations
Your solution will process a sequence of operations:
"receive"with argument[shipment_id]: Record that shipmentshipment_idhas been confirmed."getFrontier": Return the largestkwhere all values0, 1, 2, ..., khave been received. If not even0has been received, return-1."getMissing": Return a sorted list of all integers in the range[0, max_received]that have not been confirmed, wheremax_receivedis the largest shipment ID seen so far. If no shipments have been received yet, return an empty list.
Constraints
- Shipment IDs are non-negative integers up to
1,000,000. - There may be up to
100,000total operations. receiveoperations are frequent;getMissingoperations are infrequent.- The same shipment ID may be received multiple times.
Implementation Requirements
Implement a function that takes a list of operation names and corresponding arguments, executes them in order, and returns a list of results. For receive operations, append None to the results. For query operations, append the query result.
Edge Cases
- Receiving duplicate shipment IDs should not affect the state.
- Receiving a shipment ID already covered by the complete sequence has no effect.
- Large gaps between shipment IDs (e.g., receiving
0then1000000) must be handled correctly. - Queries before any shipments are received should return appropriate defaults.
Examples
Example 1
Input: delivery_monitor(['receive', 'receive', 'receive', 'getFrontier', 'getMissing', 'receive', 'getFrontier', 'getMissing'], [[0], [2], [1], [], [], [4], [], []])
Output: [None, None, None, 2, [], None, 2, [3]]
Hints
Hint 1
Track which shipment IDs have been received using a set, and maintain the highest ID seen so far separately.
Hint 2
The complete sequence endpoint only advances when the next consecutive ID becomes available—update it eagerly after each receive.
Hint 3
For gap detection, scan from just after the complete sequence endpoint up to the maximum observed ID, checking set membership.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Maintain Contiguous Delivery Sequence and Detect Gaps
Approach
The core challenge is efficiently tracking which shipments form a complete sequence starting from zero while handling arbitrary arrival order. We maintain three pieces of state:
- Confirmed set: A set containing all shipment IDs that have been received.
- Complete sequence endpoint: The largest value
kwhere every integer from0tokis in the confirmed set. Initialize to-1(meaning not even0is complete). - Highest observed ID: The maximum shipment ID seen across all receives. Initialize to
-1.
Processing Each Operation
Receive operation:
- Add the shipment ID to the confirmed set.
- Update the highest observed ID if this shipment exceeds it.
- Greedily extend the complete sequence endpoint: while the next consecutive integer (
complete_up_to + 1) exists in the confirmed set, increment the endpoint and continue checking. This ensures the endpoint always reflects the longest contiguous prefix starting at zero. - Append
Noneto the results.
Get frontier operation:
- Simply return the current complete sequence endpoint value.
Get missing operation:
- Iterate through all integers from
0tohighest_seen(inclusive). - Collect those that are not in the confirmed set.
- The iteration naturally produces a sorted list since we traverse in ascending order.
Why This Works
The invariant we maintain is: after each operation, complete_up_to equals the largest k where {0, 1, ..., k} ⊆ confirmed. The greedy advancement in the receive operation preserves this—we only increment when the next value is present, and we stop as soon as we encounter a gap.
For gap detection, every ID up to and including complete_up_to is guaranteed present, so we only need to check IDs beyond it. By scanning the full range [0, highest_seen] and filtering against the set, we correctly identify all missing values.
Complexity Analysis
Time Complexity:
- Receive: Amortized O(1). Although we have a while loop, each shipment ID can only cause the endpoint to advance once across all operations. The total advancement across all receives is bounded by the number of distinct IDs received, making the amortized cost per receive constant.
- Get frontier: O(1), a simple variable lookup.
- Get missing: O(highest_seen), as we scan from 0 to the maximum observed ID. In the worst case with large gaps, this can be expensive, but the problem states this operation is infrequent.
Space Complexity:
- O(number of distinct shipments received) for the confirmed set.
Implementation
from typing import List
def delivery_monitor(operations: List[str], arguments: List[List[int]]) -> List:
confirmed = set()
complete_up_to = -1
highest_seen = -1
results = []
for op, args in zip(operations, arguments):
if op == "receive":
shipment_id = args[0]
confirmed.add(shipment_id)
if shipment_id > highest_seen:
highest_seen = shipment_id
while complete_up_to + 1 in confirmed:
complete_up_to += 1
results.append(None)
elif op == "getFrontier":
results.append(complete_up_to)
elif op == "getMissing":
results.append([
sid for sid in range(highest_seen + 1)
if sid not in confirmed
])
else:
raise ValueError(f"Unknown operation: {op}")
return results
This solution efficiently handles the frequent receive operations while correctly answering both query types with the required behavior for edge cases like duplicates, out-of-order arrivals, and sparse ID ranges.