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 - Dynamic Programming INPUT Probability Array (prob) Coin 0 0.4 Coin 1 0.6 prob = [0.4, 0.6] target = 1 n = 2 coins P(heads) for each coin P(tails) = 1 - P(heads) Heads: 0.4, 0.6 Tails: 0.6, 0.4 ALGORITHM STEPS 1 Initialize DP dp[j] = prob of j heads 2 Base Case dp[0] = 1 (no coins yet) 3 Transition Update for each coin 4 Return dp[target] Final probability DP Table Evolution j 0 1 2 Init 1.0 0 0 Coin0 0.6 0.4 0 Coin1 0.24 0.52 0.24 dp[j] = dp[j-1]*p + dp[j]*(1-p) FINAL RESULT All Possible Outcomes S HH 0.24 HT 0.24 TH 0.28 TT 0.24 Exactly 1 head: HT: 0.4*0.4 = 0.16 TH: 0.6*0.6 = 0.36 Output: 0.52 OK Key Insight: Use DP where dp[j] represents probability of getting exactly j heads. For each coin i with probability p[i], update backwards: dp[j] = dp[j-1] * p[i] + dp[j] * (1 - p[i]). This combines cases where coin i lands heads (adding to j-1 heads) or tails (keeping j heads). Time: O(n * target), Space: O(target). TutorialsPoint - Toss Strange Coins | Dynamic Programming Approach
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