Skip to main content
All Questions

Convert Biased Coin to Fair Coin

Medium
Unlock detailed company stats for this questionUpgrade

Given a biased coin function, write another function to make it return heads or tails with equal probability.

You are given a function biased_coin() that simulates the flip of a biased coin. The function returns 1 for heads and 0 for tails with unequal probabilities. Specifically, the probability of returning heads (1) is p, and the probability of returning tails (0) is 1 - p, where p is not necessarily 0.5.

Your task is to write a new function fair_coin() that uses biased_coin() to simulate a fair coin flip. The function fair_coin() should return 1 for heads and 0 for tails with equal probability (0.5 each).

Python
def fair_coin() -> int: pass

Requirements:

  1. Use biased_coin(): You must use the biased_coin() function to implement fair_coin(). You cannot use any other random number generators or external libraries.

  2. Uniform Probability: Ensure that the fair_coin() function returns 1 and 0 with exactly equal probability.

  3. Efficiency: Aim for an efficient implementation. While there is no strict constraint on the time complexity, avoid excessive or unnecessary computations.

  4. Edge Cases: Consider edge cases such as very low or very high values of p. Ensure that your solution handles these cases correctly.

Related courses

Course

Data Analyst Interview Prep

Ace your data analyst interviews—whether you're targeting product, marketing, or business analyst roles. Tackle real take-home case studies, sharpen your technical and dashboarding skills, and get strategies from interviewers at top tech companies and startups.

Course

SQL Interviews

Prepare for SQL interviews by practicing syntax basics, aggregations, and window functions. Learn how to manipulate data, write complex queries, and analyze information from diverse data sets.