Toss Strange Coins - Problem
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
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
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
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
β 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
β 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
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code