Design a Population-Weighted Random Country Picker
Quick Overview
Design an immutable weighted random country picker whose selection probability is proportional to population. Precompute cumulative integer weights, draw uniformly over the total range, and use boundary-safe binary search with injectable randomness for deterministic tests.
Design a Population-Weighted Random Country Picker
Company: Apple
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: medium
Interview Round: Technical Screen
## Design a Population-Weighted Random Country Picker
Design a class initialized with country names and positive population weights. Each call to `pick()` must return country `i` with probability:
```text
population[i] / sum(population)
```
The country list is immutable after construction, and `pick()` will be called many times.
### Constraints & Assumptions
- `1 <= number of countries <= 200_000`.
- Country names are unique.
- Every population is a positive integer, and their sum fits in a signed 64-bit integer.
- A standard uniform pseudorandom-number source is available.
- Exact mathematical weights are required; floating-point boundary bias should be avoided when practical.
### Clarifying Questions to Ask
- Are weights fixed after initialization?
- Must results be reproducible under a supplied random seed?
- What are the maximum individual and total weights?
- Is query latency or initialization cost more important?
### Hints
- Separate one-time preprocessing from the repeated selection operation.
- Map equal-probability points in one total range onto country-specific intervals.
- Pay attention to inclusive and exclusive interval boundaries.
### What a Strong Answer Covers
- A precise mapping from a uniform draw to weighted outcomes.
- Correct boundary handling without zero-width or overlapping intervals.
- Initialization, query, and memory complexity.
- Random-source injection and deterministic unit testing.
- Tradeoffs for mutable weights or stricter constant-time sampling.
### Follow-up Questions
- How would you support frequent population updates?
- Can preprocessing produce `O(1)` expected selection time?
- How would you test distributional correctness without flaky tests?
- What goes wrong when a floating-point draw lands on a cumulative boundary?
Quick Answer: Design an immutable weighted random country picker whose selection probability is proportional to population. Precompute cumulative integer weights, draw uniformly over the total range, and use boundary-safe binary search with injectable randomness for deterministic tests.