KatInterview

Calculate Upper-Tail Probability for Binomial Distribution

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingprobabilitybinomial-distributionnumerical-methods

Last updated

Compute the exact cumulative probability P(X ≥ k) for a binomial random variable, testing understanding of numerical stability in probability calculations.

You need to compute the upper-tail probability for a binomial distribution. Given a number of independent trials n, a threshold k, and a success probability p for each trial, calculate the exact probability that a binomial random variable X ~ Binomial(n, p) takes on a value of at least k.

Mathematically, compute:

P(X ≥ k) = Σ (from i=k to n) C(n,i) * p^i * (1-p)^(n-i)

where C(n,i) denotes the binomial coefficient "n choose i".

Your implementation must handle edge cases correctly and maintain numerical stability even when intermediate values would overflow or underflow in naive implementations.

Edge case rules:

  • If k ≤ 0, return 1.0 (the probability that X is at least 0 is certain)
  • If k > n, return 0.0 (impossible to get more successes than trials)
  • If p ≤ 0.0, return 0.0 (no successes possible)
  • If p ≥ 1.0, return 1.0 (all trials succeed, so X = n ≥ k for any valid k)

Constraints:

  • 0 ≤ n ≤ 10,000
  • 0 ≤ k ≤ n + 1
  • 0.0 ≤ p ≤ 1.0
  • Your solution must be numerically stable (use logarithms to avoid overflow/underflow)
  • Return a float representing the probability

Examples

Example 1

Input: binomial_upper_tail(3, 2, 0.2)

Output: 0.1040000000000001

Example 2

Input: binomial_upper_tail(100, 40, 0.2)

Output: 0.000003608420114640808

Hints

Hint 1

Work in log-space to prevent numerical overflow when computing large factorials and powers

Hint 2

Use the log-sum-exp trick: factor out the maximum log-probability before exponentiating and summing

Hint 3

The lgamma function computes log(Γ(x)) = log((x-1)!) stably, and log1p(x) computes log(1+x) accurately for small x