MediumNo. 1230LeetCode Premium
Toss Strange Coins — LeetCode 1230 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Array, Math, Dynamic Programming, Probability and Statistics
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You have some coins. The i-th coin has a probability prob[i] of facing heads when tossed.
Example
- Input
- prob = [0.4], target = 1
- Output
- 0.40000
Python solution
class Solution:
def probabilityOfHeads(self, prob: List[float], target: int) -> float:
n = len(prob)
f = [[0] * (target + 1) for _ in range(n + 1)]
f[0][0] = 1
for i, p in enumerate(prob, 1):
for j in range(min(i, target) + 1):
f[i][j] = (1 - p) * f[i - 1][j]
if j:
f[i][j] += p * f[i - 1][j - 1]
return f[n][target]Complexity
- Time
- O(n × target)
- Space · auxiliary
- O(target)
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1230. Toss Strange Coins is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 1467 | Probability of a Two Boxes Having The Same Number of Distinct Balls | Hard |
| 1227 | Airplane Seat Assignment Probability | Medium |
| 0313 | Super Ugly Number | Medium |
| 0368 | Largest Divisible Subset | Medium |
| 0396 | Rotate Function | Medium |
| 0486 | Predict the Winner | Medium |
Frequently asked questions
- How hard is LeetCode 1230. Toss Strange Coins?
LeetCode 1230. Toss Strange Coins is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1230. Toss Strange Coins?
The Python solution on this page runs in O(n × target).
- What is the space complexity of LeetCode 1230. Toss Strange Coins?
The Python solution on this page uses O(target) auxiliary space.
- What topics does LeetCode 1230. Toss Strange Coins cover?
LeetCode 1230. Toss Strange Coins is tagged Array, Math, Dynamic Programming and Probability and Statistics on LeetCode.
- Is LeetCode 1230. Toss Strange Coins a premium problem?
Yes. LeetCode 1230. Toss Strange Coins is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.