Generate uniform 0–6 from biased coin
Company: LinkedIn
Role: Machine Learning Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of randomized algorithms, probability theory, and techniques for extracting uniform randomness from a biased source.
Constraints
- 1 <= len(stream) <= 100000
- Each element of `stream` is either 0 or 1
- The provided stream is guaranteed to contain enough values to generate one final answer
- Your logic must not depend on the value of `p`
Examples
Input: [0,1,0,1,1,0]
Expected Output: 1
Explanation: Pairs are `01 -> 0`, `01 -> 0`, `10 -> 1`, so the unbiased bits are `001`, which is 1.
Input: [1,0,1,0,0,1]
Expected Output: 6
Explanation: Pairs are `10 -> 1`, `10 -> 1`, `01 -> 0`, so the unbiased bits are `110`, which is 6.
Input: [1,0,1,0,1,0,0,1,1,0,1,0]
Expected Output: 3
Explanation: First three unbiased bits are `111`, which is 7, so they are rejected. The next three unbiased bits are `011`, which is 3.
Input: [0,0,1,1,0,1,1,1,1,0,0,0,0,0,0,1]
Expected Output: 2
Explanation: Discard `00`, discard `11`, then `01 -> 0`; discard `11`, then `10 -> 1`; discard `00`, discard `00`, then `01 -> 0`. The unbiased bits are `010`, which is 2.
Input: [1,1,1,0,0,0,0,1,1,0]
Expected Output: 5
Explanation: Discard `11`, then `10 -> 1`; discard `00`, then `01 -> 0`; then `10 -> 1`. The unbiased bits are `101`, which is 5.
Input: [0,1,0,1,0,1]
Expected Output: 0
Explanation: Pairs are `01 -> 0`, `01 -> 0`, `01 -> 0`, so the unbiased bits are `000`, which is 0.
Hints
- A pair of outcomes `01` and `10` have the same probability, even when the coin is biased.
- Once you can generate fair bits, think about creating a value in `[0,7]` and using rejection sampling.