Implement weighted random choice
Company: Pinterest
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates understanding of weighted random sampling, probability distributions, input validation, and algorithmic time and space complexity in the context of implementing a sampling routine.
Part 1: Deterministic Weighted Random Choice for One Sample
Constraints
- `1 <= len(items) <= 10^5` for valid inputs
- If `p` is not `None`, then `len(p) == len(items)`
- Each probability must be a non-negative number
- For valid weighted input, `abs(sum(p) - 1.0) <= 1e-9`
- `0 <= r < 1`
Examples
Input: (['red', 'green', 'blue'], [0.1, 0.3, 0.6], 0.35)
Expected Output: 'green'
Explanation: Cumulative probabilities are 0.1, 0.4, 1.0. Since 0.35 < 0.4, the answer is 'green'.
Input: ([10, 20, 30, 40], None, 0.74)
Expected Output: 30
Explanation: Uniform buckets are [0,0.25), [0.25,0.5), [0.5,0.75), [0.75,1). 0.74 falls in the third bucket.