Review Constant-Time Random Courier Selection and Removal
DoorDashSoftware Engineer · OnsiteLast updated
Maintain dense map indices for uniform random selection and swap-with-last removal, including empty states, concurrency, and complexity checks.
Review a delivery-assignment service that stores couriers in dasher_map under contiguous integer keys starting at 0. add_dasher inserts a courier. pick_dasher chooses a courier at random and removes it. adjust_map restores contiguous keys by moving the last entry into a removed slot.
Explain the invariants and constant-time operations needed for this design, the bugs you would look for, and the code-quality improvements you would request in a review.
Requirements and Constraints
- After each operation, the map keys must be exactly
0throughn - 1, wherenis the number of stored entries. - Selection should be uniform over the currently stored entries.
- Preserve the original operations' expected or amortized constant-time behavior; do not repair the map by scanning and renumbering every entry.
- An external delivery-recording service can be assumed to work correctly.
- No actual implementation is supplied here, so identify failure modes and required behavior rather than claiming a particular unseen line is wrong.
Clarifying Questions
- What should selection do when the map is empty?
- May the same courier identity be added more than once, or must insertion reject duplicates?
- Can calls occur concurrently, and must selecting and removing a courier be one atomic operation?
- Which method owns the size update, and when is the selected courier sent to the recording service?
Hints
Hint 1
Save the selected entry before replacing its slot: The last entry may move into the selected index. The courier returned or recorded must still be the one originally selected.
Follow-up questions
- What is different when the randomly selected key is already the final key?
- Why can moving the last entry preserve uniform selection on the next call?
- How could a duplicate courier identity change the meaning of uniform selection?
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.