Design Insert/Delete/GetRandom with Weighted Sampling
Design a data structure that supports inserting values, deleting values, and returning a random value with uniform probability. Then, extend this data structure to support weighted sampling, where getRandom returns values with a probability proportional to their assigned weights.
Constraints & Assumptions:
- Values are unique unless clarified.
- Unweighted operations (insert, delete, getRandom) should achieve O(1) average time complexity.
- Weighted sampling (
getRandomwith weights) can be O(log n) time complexity, unless the interviewer specifies O(1). - Weights are positive numbers.
Follow-up Questions:
- How would you support duplicate values?
- How would you handle updating the weight of an existing value?
- How would you test the distribution of the random sampling to ensure correctness?
- Under what conditions would an alias table be a more suitable approach than a Fenwick tree (or similar structure)?
AI interview prep
Core dilemma
Balancing efficient O(1) average time for basic operations (insert, delete, uniform random) with the complexity of weighted sampling, which often introduces logarithmic or more complex time dependencies.
3 tradeoffs and 2 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Design Insert/Delete/GetRandom with Weighted Sampling
Design a data structure that supports inserting values, deleting values, and returning a random value with uniform probability. Then, extend this data structure to support weighted sampling, where getRandom returns values with a probability proportional to their assigned weights.
Constraints & Assumptions:
- Values are unique unless clarified.
- Unweighted operations (insert, delete, getRandom) should achieve O(1) average time complexity.
- Weighted sampling (
getRandomwith weights) can be O(log n) time complexity, unless the interviewer specifies O(1). - Weights are positive numbers.
Follow-up Questions:
- How would you support duplicate values?
- How would you handle updating the weight of an existing value?
- How would you test the distribution of the random sampling to ensure correctness?
- Under what conditions would an alias table be a more suitable approach than a Fenwick tree (or similar structure)?