KatInterview

Calculate Binomial Cumulative Probability for Limited Supply

Math & Bit ManipulationAuto-graded · 19 test cases
EasyAuto-gradedMath & Bit Manipulationprobabilitybinomial-distributioncombinatorics

Last updated

Tests understanding of binomial distributions and computing cumulative probabilities for discrete independent events.

You are modeling demand at a service counter where each of n visitors independently decides to make a purchase with probability p. The counter has limited stock and can fulfill at most 2 purchase requests.

Write a function that calculates the probability that the counter can satisfy all purchase requests. In other words, compute the probability that the number of visitors who decide to purchase is at most 2.

Assume purchase decisions follow a binomial distribution with parameters n (number of visitors) and p (probability each visitor makes a purchase).

Task

Given:

  • n: the total number of visitors (integer)
  • p: the probability that any single visitor makes a purchase (float between 0 and 1)

Return the probability that 0, 1, or 2 visitors make a purchase.

Constraints

  • 0 <= n <= 1000
  • 0.0 <= p <= 1.0
  • Return the result as a floating-point number
  • When n < 2, the counter can always satisfy demand (all outcomes have at most n purchases)

Examples

Example 1

Input: binomial_prob_at_most_two(5, 0.5)

Output: 0.5

Example 2

Input: binomial_prob_at_most_two(2, 0.5)

Output: 1

Example 3

Input: binomial_prob_at_most_two(5, 0.2)

Output: 0.9420800000000003

Example 4

Input: binomial_prob_at_most_two(5, 0.8)

Output: 0.05791999999999997

Hints

Hint 1

The number of purchases follows a binomial distribution B(n, p). You need to sum probabilities for k = 0, 1, and 2 purchases.

Hint 2

The binomial probability mass function is P(X = k) = C(n, k) × p^k × (1 - p)^(n - k), where C(n, k) is the binomial coefficient.

Hint 3

When p = 0.5, the distribution is symmetric around n/2. This can help you verify your answer for special cases.