Toss Strange Coins — LeetCode 1230 Python Solution

MediumLeetCode PremiumArrayMathDynamic ProgrammingProbability and Statistics
Problem
#1230
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n \times target)
SpaceO(target) auxiliary

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

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 \times 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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview