Soup Servings — LeetCode 808 Python Solution

MediumMathDynamic ProgrammingProbability and Statistics
Problem
#808
Reading time
4 min

The problem

You have two soups, A and B, each starting with n mL. On every turn, one of the following four serving operations is chosen at random, each with probability 0.25 independent of all previous turns: pour 100 mL from type A and 0 mL from type B pour 75 mL from type A and 25 mL from type B pour 50 mL from type A and 50 mL from type B pour 25 mL from type A and 75 mL from type B Note: There is no operation that pours 0 mL from A and 100 mL from B.

Example

Input
n = 50
Output
0.62500
Explanation
If we perform either of the first two serving operations, soup A will become empty first.

Python solution

Python
class Solution:
    def soupServings(self, n: int) -> float:
        @cache
        def dfs(i: int, j: int) -> float:
            if i <= 0 and j <= 0:
                return 0.5
            if i <= 0:
                return 1
            if j <= 0:
                return 0
            return 0.25 * (
                dfs(i - 4, j)
                + dfs(i - 3, j - 1)
                + dfs(i - 2, j - 2)
                + dfs(i - 1, j - 3)
            )

        return 1 if n > 4800 else dfs((n + 24) // 25, (n + 24) // 25)

Complexity

MeasureComplexity
TimeO(C^2)
SpaceO(C^2) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 808. Soup Servings 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 808. Soup Servings?
LeetCode 808. Soup Servings is rated Medium on LeetCode.
What is the time complexity of LeetCode 808. Soup Servings?
The Python solution on this page runs in O(C^2).
What is the space complexity of LeetCode 808. Soup Servings?
The Python solution on this page uses O(C^2) auxiliary space.
What topics does LeetCode 808. Soup Servings cover?
LeetCode 808. Soup Servings is tagged Math, Dynamic Programming and Probability and Statistics on LeetCode.

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