FastPrepBiased Coin: Probability of Exactly h Heads

Biased Coin: Probability of Exactly h Heads

Akuna Capital logoAkuna Capital● EasyINTERNPHONE SCREEN

Problem statement

A biased coin lands heads with probability p and tails with probability 1 - p. You toss it n times, and the tosses are independent.

Return the probability that exactly h of the tosses are heads, so the other n - h are tails. Answers within 10^-9 of the exact value are accepted.

Function

exactHeadsProbability(n: int, h: int, p: double) → double

Examples

Example 1

n = 10h = 5p = 0.7return = 0.1029193452

This is the interview case. One order with five heads and five tails has probability 0.7^5 * 0.3^5 = 0.16807 * 0.00243. There are C(10, 5) = 252 such orders, so the answer is 252 * 0.16807 * 0.00243 = 0.1029193452.

Example 2

n = 3h = 2p = 0.5return = 0.375

With a fair coin, the eight results are equally likely. HHT, HTH and THH have exactly two heads, so the answer is 3/8 = 0.375.

Example 3

n = 4h = 3p = 0.6return = 0.3456

Each order with three heads and one tail has probability 0.6^3 * 0.4 = 0.0864. The tail can be any of the four tosses, so the answer is 4 * 0.0864 = 0.3456.

Constraints

  • 1 <= n <= 1000
  • 0 <= h <= n
  • 0 <= p <= 1

More Akuna Capital problems

See Akuna Capital hiring insights
Saved
public double exactHeadsProbability(int n, int h, double p) {
    // Write your code here.
}
Checking account…