Exact Binomial Probability of Coin Flips
Math & Bit ManipulationAuto-graded · 26 test casesLast updated
Calculates the exact binomial probability of obtaining a specific number of heads across a series of fair coin tosses.
Given a total number of fair coin flips n and a target number of heads k, calculate the exact probability of obtaining precisely k heads.
A coin flip is fair, meaning the probability of landing heads on any single flip is $0.5$, and each flip is mutually independent.
The probability follows the binomial distribution formula:
$$P(X = k) = \binom{n}{k} p^k (1-p)^{n-k}$$
Since $p = 0.5$, this simplifies to:
$$P(X = k) = \frac{\binom{n}{k}}{2^n}$$
If k is less than $0$ or greater than n, or if n is negative, return 0.0.
Constraints
- $-10^9 \le n \le 1000$
- $-10^9 \le k \le 1000$
Examples
Example 1
Input: probability_exactly_k_heads(10, 7)
Output: 0.1171875
Example 2
Input: probability_exactly_k_heads(10, 0)
Output: 0.0009765625
Example 3
Input: probability_exactly_k_heads(10, 10)
Output: 0.0009765625
Example 4
Input: probability_exactly_k_heads(4, 2)
Output: 0.375
Hints
Hint 1
Use the binomial distribution formula with p = 0.5.
Hint 2
Check for out-of-bounds inputs where k is negative or exceeds n.
Hint 3
In Python, `math.comb(n, k)` conveniently computes the combination n choose k.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To compute the probability of observing exactly $k$ heads out of $n$ independent flips of a fair coin:
- Check Boundary Conditions: If $k < 0$, $k > n$, or $n < 0$, it is impossible to observe $k$ heads, so we return
0.0. - Apply Combinatorics: The number of ways to pick $k$ heads out of $n$ flips is given by the binomial coefficient $\binom{n}{k} = \frac{n!}{k!(n-k)!}$.
- Compute Probability: Each outcome sequence of $n$ flips occurs with equal likelihood $(0.5)^n = 2^{-n}$. Multiplying the number of successful outcomes by the probability of a single sequence yields the total probability:
$$\text{Probability} = \binom{n}{k} \cdot 0.5^n$$
Complexity Analysis
- Time Complexity: $\mathcal{O}(\min(k, n - k))$ using efficient combination algorithms like
math.comb. - Space Complexity: $\mathcal{O}(1)$ auxiliary space.
import math
def probability_exactly_k_heads(flips: int, heads: int) -> float:
if heads < 0 or heads > flips or flips < 0:
return 0.0
return math.comb(flips, heads) * (0.5 ** flips)