Leetcode #808: Soup Servings
In this guide, we solve Leetcode #808 Soup Servings in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Math, Dynamic Programming, Probability and Statistics
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: n = 50
Output: 0.62500
Explanation:
If we perform either of the first two serving operations, soup A will become empty first.
If we perform the third operation, A and B will become empty at the same time.
If we perform the fourth operation, B will become empty first.
So the total probability of A becoming empty first plus half the probability that A and B become empty at the same time, is 0.25 * (1 + 1 + 0.5 + 0) = 0.625.
Python Solution
class Solution:
def soupServings(self, n: int) -> float:
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.