You are given access to a biased coin through get_random_01_biased(), which returns 1 with some unknown fixed probability p (where 0 < p < 1) and 0 with probability 1 - p. Implement fair_coin_toss() so that it uses only this biased source yet returns 0 or 1, each with probability exactly 0.5, regardless of p.
For deterministic testing, your function receives a list tosses of pre-generated biased outcomes (each 0 or 1). Consume values from the front of the list (in order) as if calling get_random_01_biased() repeatedly, and return a single fair bit 0 or 1. If the list is exhausted before a fair result can be produced, return -1.
The classic technique is von Neumann's trick: consider consecutive pairs of biased tosses. The pair (0, 1) and the pair (1, 0) each occur with probability p(1 - p), so they are equally likely. Use one of these pairs to decide the fair output and discard the others.
Function Signature
def fair_coin_toss(tosses: list[int]) -> int:
Rules
-
Read
tosses
from the front in non-overlapping pairs: positions 0 and 1, then 2 and 3, and so on.
-
The first pair whose two values differ decides the result. The pair
(0, 1)
returns
0
and the pair
(1, 0)
returns
1
. Pairs
(0, 0)
and
(1, 1)
are discarded.
-
If the list runs out before a deciding pair appears, return
-1
. In an odd-length list the last toss has no partner and is ignored.
Constraints
-
1 <= tosses.length <= 10^5
-
tosses[i]
is
0
or
1
Examples
Input: tosses = [0,1,0,0,1,1]
Output: 0
The first pair (0, 1) immediately produces the fair output 0, and the rest of the list is never read.
Input: tosses = [1,1,0,0,1,0]
Output: 1
The pair (1, 1) is discarded, the pair (0, 0) is discarded, and the pair (1, 0) produces the fair output 1.
Input: tosses = [0,0,1]
Output: -1
The pair (0, 0) is discarded and the final 1 has no partner, so no fair result can be produced. Pairing the second and third tosses would give (0, 1), but that pair overlaps the one already used.