Generate an Unbiased Bit from a Biased Coin
Updated
Problem statement
An unknown biased coin returns heads with probability p and tails with probability 1 - p, where 0 < p < 1. Consecutive flips are independent.
The array flips is a recorded prefix of coin tosses, where 1 means heads and 0 means tails. Read non-overlapping pairs from left to right:
- For
[1,0], return0. - For
[0,1], return1. - For
[0,0]or[1,1], discard the pair and continue.
The input is guaranteed to contain a differing pair. Return the unbiased bit produced by the first such pair.
Function
generateUnbiasedBit(flips: int[]) → intExamples
Example 1
flips = [1,0]return = 0The first pair is heads-tails, so the method returns 0.
Example 2
flips = [1,1,0,1]return = 1The equal pair [1,1] is discarded. The next pair is tails-heads, which returns 1.
Example 3
flips = [0,0,1,1,1,0]return = 0The first two equal pairs are discarded. The final heads-tails pair returns 0.
Constraints
2 <= flips.length <= 200000.flips.lengthis even.- Every value in
flipsis either0or1. - At least one non-overlapping pair contains different values.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Moving Cost by Volume and CategoryWayfair · ONSITE INTERVIEWWayfair interview questions
- Estimate Pi from Uniform SamplesMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Add Two Numbers Given as Digit ArraysCapital One · ONSITE INTERVIEWCapital One interview questions
- Expected Value of Modified DiceJane Street · ONSITE INTERVIEWJane Street interview questions
- Deterministic K-Means AssignmentsMeta · PHONE SCREEN · ONSITE INTERVIEWMeta interview questions
- Group-Relative Policy AdvantagesAmazon · ONSITE INTERVIEW
- Reservoir Sampling with Recorded DrawsStackAdapt · ONSITE INTERVIEWStackAdapt interview questions
- Sliding-Window Averages as Reduced FractionsCoinbase · ONSITE INTERVIEWCoinbase interview questions
- Tensor-Parallel MLP GradientsOpenAI · ONSITE INTERVIEWOpenAI interview questions
- Vectorized K-Means AssignmentsSambaNova Systems · ONSITE INTERVIEWSambaNova Systems interview questions