← 返回 doordash 的题目列表Debug a Random Dasher Picker
类型:online_judge
Implement and debug a thread-safe random Dasher picker, RandomDasherPicker. The component maintains Dashers that are currently available for assignments and supports dynamic insertion, removal, and random selection.
Implement:
add(dasher_id): Add a Dasher. Do nothing if it already exists.
remove(dasher_id): Remove a Dasher. Do nothing if it does not exist.
pick(): Return a uniformly random current dasher_id; return null if no Dasher is available.
The initial design stores Dashers in an index -> dasher_id mapping. To keep indices contiguous, when deleting a Dasher, move the last Dasher into the deleted index and then remove the old last index.
Requirements:
add, remove, and pick must each run in average O(1) time.
No holes may remain in the index range after deletion.
The component is called concurrently. It must not return a removed Dasher, throw concurrent-modification errors, or corrupt internal state.
Do not invoke potentially blocking external APIs while holding the component's internal lock. Explain how a downstream call after pick should be structured.
Example:
add("A")
add("B")
add("C")
remove("B")
The resulting set is {"A", "C"}. A valid internal representation is:
0 -> "A"
1 -> "C"
pick() may return only "A" or "C".
Constraints: up to 10^5 Dashers and 10^6 operations.
Example
Input
add A\nadd B\npick
Output
A 或 B