Track the Contiguous Package Frontier and Missing IDs
AmazonSoftware Engineer · Technical ScreenLast updated
This problem tests your ability to manage sparse, out-of-order data using data structures like sets or priority queues and finding gaps within a contiguous range.
Problem Statement
You are building a PackageTracker class that receives delivery notifications as individual integers (package IDs). Packages arrive in an arbitrary order and may contain duplicates. The system needs to track the "delivered frontier" (the largest integer k such that all package IDs from 0 to k have been received) and identify all missing IDs between 0 and the current maximum observed ID.
Implement the following methods:
void receive(int packageId): Records that a package has arrived.int getFrontier(): Returns the largestksuch that all IDs0throughkare present.List getMissing(): Returns a sorted list of all missing IDs between0and the maximum observedpackageId.
Constraints
packageIdcan be any non-negative integer up to1,000,000.receiveis called frequently;getMissingis called occasionally.
Example
tracker = PackageTracker()
tracker.receive(0)
tracker.receive(2)
tracker.receive(1)
# Frontier is 2. Missing is [].
tracker.receive(4)
# Frontier is 2. Missing is [3].
Edge Cases
- Receiving the same
packageIdmultiple times. - Receiving a
packageIdthat is smaller than the current frontier. - Large gaps between IDs (e.g., receiving 0, then 1,000,000).
Hints
Hint 1
Use a boolean array or a set to track which packages have been received so far.
Hint 2
Maintain a pointer for the frontier that only increments when the next expected integer is found in your tracker.
Hint 3
For `getMissing`, iterate from the frontier + 1 up to the maximum observed ID and check your tracking structure.
Follow-up questions
- How would you optimize `getMissing` if the range is extremely sparse and the maximum ID is very large?
- If memory were limited, how could you handle millions of package IDs arriving in a distributed system?
- What is the time complexity of `receive` and `getMissing`, and can you improve them using a segment tree or a disjoint set union?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.