You have some coins. The i-th coin has a probability prob[i] of facing heads when tossed.

Return the probability that the number of coins facing heads equals target if you toss every coin exactly once.

Note: The answer should be accurate to within 10^-5 of the expected answer.

Input & Output

Example 1 — Basic Case
$ Input: prob = [0.4, 0.6], target = 1
Output: 0.52
💡 Note: Two ways to get exactly 1 head: coin 1 heads + coin 2 tails (0.4 × 0.4 = 0.16) or coin 1 tails + coin 2 heads (0.6 × 0.6 = 0.36). Total: 0.16 + 0.36 = 0.52
Example 2 — All Heads
$ Input: prob = [0.5, 0.5, 0.5], target = 3
Output: 0.125
💡 Note: Need all 3 coins to be heads: 0.5 × 0.5 × 0.5 = 0.125
Example 3 — Impossible Target
$ Input: prob = [0.2, 0.3], target = 5
Output: 0.0
💡 Note: Cannot get 5 heads with only 2 coins, so probability is 0

Constraints

  • 1 ≤ prob.length ≤ 1000
  • 0 ≤ prob[i] ≤ 1
  • 0 ≤ target ≤ prob.length
  • Answers within 10-5 of expected answer will be accepted

Visualization

Tap to expand
Toss Strange Coins: Find Probability of Exact Head CountInputCoin 1P(H)=0.4Coin 2P(H)=0.6Target = 1All OutcomesHHHT ✓TH ✓TT0.240.160.360.24Sum probabilities where exactly 1 head occursResult: 0.520.16 + 0.36 = 0.52
Understanding the Visualization
1
Input
Array of coin head probabilities and target count
2
Process
Calculate probability of all combinations yielding target heads
3
Output
Sum of probabilities where heads count equals target
Key Takeaway
🎯 Key Insight: Build probability table incrementally - each coin either contributes to heads count or doesn't, and we sum all valid combinations
Asked in
Google 25 Facebook 18 Microsoft 15
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen