Probability of Consecutive Heads
Problem statement
Toss a fair coin n times. Each toss is heads (H) or tails (T) with equal probability, and the tosses are independent.
Return the probability that the result has two heads in a row (HH) at least once. Answers within 10^-9 of the exact value are accepted.
Function
consecutiveHeadsProbability(n: int) → doubleExamples
Example 1
n = 2return = 0.25The four equally likely results are HH, HT, TH and TT. Only HH has two heads in a row, so the probability is 1/4 = 0.25.
Example 2
n = 3return = 0.375Of the 8 results, HHH, HHT and THH have two heads in a row. HTH has two heads, but they are not next to each other. The probability is 3/8 = 0.375.
Example 3
n = 5return = 0.59375There are 32 results, and 13 of them have no two heads in a row. The other 19 do, so the probability is 19/32 = 0.59375.
Constraints
1 <= n <= 1000