← back

Binomial Distribution Probability

#79 · Probability · Medium

⊣ Solve on deep-ml.com

Problem

Calculate the probability of getting exactly k successes in n independent Bernoulli trials, each with probability p of success, using the binomial distribution formula.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def binomial_probability(n, k, p):
    # Compute binomial coefficient C(n, k)
    def comb(n, k):
        if k < 0 or k > n:
            return 0
        if k == 0 or k == n:
            return 1
        k = min(k, n - k)
        result = 1
        for i in range(k):
            result = result * (n - i) // (i + 1)
        return result

    probability = comb(n, k) * (p ** k) * ((1 - p) ** (n - k))
    return round(probability, 4)

Explanation

  1. The binomial probability formula is: P(X = k) = C(n, k) p^k (1-p)^(n-k).
  2. C(n, k) is the binomial coefficient (number of ways to choose k items from n).
  3. p^k is the probability of k successes.
  4. (1-p)^(n-k) is the probability of (n-k) failures.
  5. The product gives the probability of any specific arrangement of k successes, multiplied by the number of such arrangements.

Complexity

  • Time: O(k) for computing the binomial coefficient
  • Space: O(1)