Simulate Uniform(0,1) from random bits
Company: Google
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This Coding & Algorithms question for a Data Scientist evaluates understanding of randomized algorithms, bit-level representation of real numbers, and probabilistic error and time-complexity analysis, situated at an algorithmic and mathematical abstraction level that requires both conceptual design and quantitative reasoning.
Constraints
- `0 <= len(bits) <= 30`
- Each `bits[i]` is either `0` or `1`
- The simple randomized algorithm uses exactly `n` calls to `rand_bit()` for `n` output bits
Examples
Input: ([],)
Expected Output: 0.0
Explanation: With no bits, the binary fraction has no nonzero terms, so the value is 0.0.
Input: ([1],)
Expected Output: 0.5
Explanation: The fraction is `1/2 = 0.5`.
Input: ([1, 0, 1],)
Expected Output: 0.625
Explanation: This is `1/2 + 0/4 + 1/8 = 0.625`.
Input: ([0, 1, 1, 0],)
Expected Output: 0.375
Explanation: This is `0/2 + 1/4 + 1/8 + 0/16 = 0.375`.
Input: ([1, 1, 1, 1],)
Expected Output: 0.9375
Explanation: This is `1/2 + 1/4 + 1/8 + 1/16 = 15/16 = 0.9375`.
Hints
- Think of the list as the binary digits after the point: `[1, 0, 1]` means `0.101` in base 2.
- You can build an integer from the bits and divide by `2^n`, or accumulate the value with weights `1/2, 1/4, 1/8, ...`.