Two pots hold soup A and soup B, with n millilitres in each. On every turn, one of four servings is chosen at random, each with chance 1/4: 100 mL of A and none of B; 75 mL of A and 25 of B; 50 of each; or 25 mL of A and 75 of B. Both amounts are served at the same moment. If a pot has less than asked, all of it is served.
Serving stops right after the first turn in which a pot is empty. Return the chance that A empties before B, plus half the chance that both empty on the same turn. Answers within 0.00001 of the true value count as correct.
Example 1
Input: n = 40 Output: 0.625 Why: two servings empty A, one empties both, one empties B
2 more examples and the constraints
Example 2
Input: n = 120 Output: 0.7421875 Why: more soup means more turns, and A drains faster
Example 3
Input: n = 0 Output: 0.5 Why: both pots are empty from the start, which counts half
Constraints
- 0 ≤ n ≤ 1,000,000,000
- Note that no serving takes only from B
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion with a memoO(m²)
- Bottom-up tableO(m²)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Work at n = 4,800 (m = 192) | Verdict |
|---|---|---|---|
| Recursion with a memo | O(m²) | Passes; recursion and memo checks | |
| Bottom-up table | O(m²) | Best; plain loops, no stack |
m = ceil(min(n, 4,800) / 25), the soup per pot in 25 mL units.
Edge cases to test
- n = 0. Both pots start empty, which counts as a tie: 0.5.
- Amounts that are not multiples of 25. Round up: 26 mL is two units, because the last 1 mL still needs a serving.
- Huge n. n can be 10⁹. Without the cut-off the table would have over 10¹⁵ cells.
- Exactly 4,800. Still computed by the DP; the shortcut starts just above it.
Common mistakes
- Rounding n / 25 down, which turns 1 to 24 mL into no soup at all.
- Running the DP for every n up to 10⁹ instead of returning 1 for large n.
- Giving the "both empty" case 1 instead of 0.5, or the "only B empty" case 0.5.
How to talk through it
- 1Clarify. What counts when both empty together? How exact must the answer be?
- 2Shrink the state. Every serving is a multiple of 25, so work in units of 25 mL with amounts rounded up.
- 3Write the recurrence. f(a, b) is the average of the four states one serving away, with three base cases for empty pots.
- 4Handle huge n. A drains faster on average, so the answer heads to 1; past 4,800 mL it is within the error bound.
- 5Test out loud. Check n = 0 gives 0.5 and n = 40 gives 0.625.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?