You are conducting a fascinating probability experiment with strange coins! Each coin has its own unique probability of landing heads when tossed. Given an array prob where prob[i] represents the probability that the i-th coin shows heads, you need to calculate the probability that exactly target coins will show heads when you toss all coins once.

For example, if you have 3 coins with probabilities [0.4, 0.5, 0.1] and want exactly 1 head, you need to consider all possible ways to get exactly 1 head and sum their probabilities.

Goal: Return the probability (as a decimal) that exactly target coins will show heads.

Input & Output

example_1.py β€” Python
$ Input: prob = [0.4, 0.5, 0.1], target = 1
β€Ί Output: 0.48
πŸ’‘ Note: There are 3 ways to get exactly 1 head: HTT (0.4Γ—0.5Γ—0.9=0.18), THT (0.6Γ—0.5Γ—0.9=0.27), TTH (0.6Γ—0.5Γ—0.1=0.03). Total: 0.18+0.27+0.03=0.48
example_2.py β€” Python
$ Input: prob = [0.5, 0.5, 0.5], target = 2
β€Ί Output: 0.375
πŸ’‘ Note: With 3 fair coins wanting 2 heads: HHT, HTH, THH each have probability 0.5Γ—0.5Γ—0.5=0.125. Total: 3Γ—0.125=0.375
example_3.py β€” Python
$ Input: prob = [1.0], target = 1
β€Ί Output: 1.0
πŸ’‘ Note: Edge case: With one coin that always shows heads, the probability of getting exactly 1 head is 1.0

Visualization

Tap to expand
Probability Cascade Visualization1.0Start: 0 headsCoin 1 (p=0.4)0.60 heads0.41 headCoin 2 (p=0.5)0.30 heads0.51 head0.22 headsFinal Result0.48Exactly 1 head🎯 Key Insight: Dynamic Programming builds probabilities incrementallyEach coin redistributes existing probabilities between head counts
Understanding the Visualization
1
Start with Certainty
Begin with 100% probability of 0 heads
2
First Coin Split
Probability splits: some flows to 1 head, rest stays at 0 heads
3
Continue Cascade
Each subsequent coin further splits and redistributes probabilities
4
Final Collection
Collect the probability that flows to exactly the target number of heads
Key Takeaway
🎯 Key Insight: Dynamic programming transforms an exponential problem into a polynomial one by building probabilities incrementally rather than enumerating all possible outcomes.

Time & Space Complexity

Time Complexity
⏱️
O(n * target)

We process each of n coins and for each coin, we update at most target+1 probability values

n
2n
βœ“ Linear Growth
Space Complexity
O(target)

We can optimize space by using only two arrays of size target+1, or even one array with careful updating

n
2n
βœ“ Linear Space

Constraints

  • 1 ≀ prob.length ≀ 1000
  • 0 ≀ prob[i] ≀ 1
  • 0 ≀ target ≀ prob.length
  • Answers within 10-5 of the actual value will be accepted as correct
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
28.5K 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