KatInterview

Maintain Contiguous Delivery Sequence and Detect Gaps

Data Structure DesignAuto-graded · 14 test cases
MediumAuto-gradedData Structure Designsetstrackingstate-management

Last 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:

  1. Complete Sequence Endpoint: What is the largest value k such that every integer from 0 through k has been confirmed?
  2. Gap Detection: Which integers between 0 and the highest confirmed value are still missing?

Operations

Your solution will process a sequence of operations:

  • "receive" with argument [shipment_id]: Record that shipment shipment_id has been confirmed.
  • "getFrontier": Return the largest k where all values 0, 1, 2, ..., k have been received. If not even 0 has been received, return -1.
  • "getMissing": Return a sorted list of all integers in the range [0, max_received] that have not been confirmed, where max_received is 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,000 total operations.
  • receive operations are frequent; getMissing operations 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 0 then 1000000) 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.