KatInterview

Exact Binomial Probability of Coin Flips

Math & Bit ManipulationAuto-graded · 26 test cases
EasyAuto-gradedMath & Bit Manipulationmathprobabilitycombinatorics

Last 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.