KatInterview

Binomial Probability of Exactly k Successes

Arrays & HashingAuto-graded · 24 test cases
EasyAuto-gradedArrays & Hashingprobabilitycombinatoricsmath

Last updated

Tests whether a candidate can implement the binomial PMF, including the combination factor, a bias parameter, and out-of-range edge cases.

Binomial Probability of Exactly k Successes

You are running a series of n independent trials. On each trial the outcome is either a success or a failure. The probability of success on any single trial is p, and this value stays the same across all trials.

Given n, k, and p, return the probability that the number of successes equals exactly k.


Background

Because every trial is independent, the probability of one particular ordering that contains exactly k successes and n − k failures is:

p^k × (1 − p)^(n − k)

However, there are many orderings that produce the same count of k successes. The number of ways to choose which k of the n trials are successes is the binomial coefficient:

C(n, k) = n! / (k! × (n − k)!)

Multiplying these two quantities gives the binomial probability mass function (PMF):

P(X = k) = C(n, k) × p^k × (1 − p)^(n − k)

Task

Implement a function that evaluates this formula for the given inputs and returns the result as a float.

If k is outside the range [0, n], return 0.0.


Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ k ≤ n (the function must also handle values of k outside this range gracefully)
  • 0.0 ≤ p ≤ 1.0
  • The answer will fit in a standard 64-bit float; no special big-number handling is required.
  • Do not use any statistical library functions (e.g., scipy.stats.binom.pmf); compute the result directly from the formula.

Examples

Example 1

Input: binomial_pmf(5, 2, 0.5)

Output: 0.3125

Example 2

Input: binomial_pmf(5, 2, 0.7)

Output: 0.13230000000000006

Example 3

Input: binomial_pmf(10, 0, 0.3)

Output: 0.028247524899999984

Example 4

Input: binomial_pmf(10, 10, 0.3)

Output: 0.0000059048999999999975

Hints

Hint 1

The binomial coefficient C(n, k) counts the number of distinct orderings of k successes among n trials — Python's math.comb(n, k) computes this exactly with integers, avoiding floating-point rounding in that step.

Hint 2

Check whether k is negative or greater than n before doing any arithmetic; both cases have zero valid orderings and should return 0.0 immediately.

Hint 3

The full formula is just three factors multiplied together: the combination count, p raised to the power k, and (1 − p) raised to the power (n − k). Assemble them in that order and you are done.