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. The amounts from A and B are poured simultaneously during the turn. If an operation asks you to pour more than you have left of a soup, pour all that remains of that soup. The process stops immediately after any turn in which one of the soups is used up.

Return the probability that A is used up before B, plus half the probability that both soups are used up in the same turn.

Answers within 10-5 of the actual answer will be accepted.

Input & Output

Example 1 — Small Case
$ Input: n = 50
Output: 0.625
💡 Note: With 50mL each, there are limited serving combinations. A has higher probability of finishing first due to higher average serving rate (62.5 vs 37.5 mL per turn).
Example 2 — Medium Case
$ Input: n = 100
Output: 0.71875
💡 Note: With 100mL each, the probability increases as the law of large numbers makes A's higher serving rate more apparent.
Example 3 — Large Case
$ Input: n = 5000
Output: 1.0
💡 Note: For large n, A's 67% higher serving rate means it will almost certainly finish first. The probability approaches 1.0.

Constraints

  • 0 ≤ n ≤ 109

Visualization

Tap to expand
Soup Servings Problem INPUT Soup A 50 mL Soup B 50 mL n = 50 4 Operations (25% each): 1: A-100, B-0 2: A-75, B-25 3: A-50, B-50 4: A-25, B-75 A depletes faster on avg (avg: A-62.5, B-37.5) ALGORITHM STEPS 1 Scale Down n=50 --> units: ceil(50/25)=2 2 DP/Memoization States: (a,b) soup amounts 3 Recursion P(a,b) = 0.25 * sum(4 ops) 4 Base Cases A empty first: 1.0 Both empty: 0.5 B empty first: 0.0 Probability Calculation State(2,2): Start Op1: (0,2)-->A empty=1.0 Op2: (0,1)-->A empty=1.0 Op3: (0,0)-->Both=0.5 Op4: (1,0)-->B empty=0.0 FINAL RESULT 0.625 62.5% Probability Breakdown P(A first) = 0.50 P(Both) = 0.25 0.50 + 0.5*0.25 = 0.625 Output 0.625 OK - Verified Key Insight: Mathematical Optimization Soup A depletes faster on average (62.5mL vs 37.5mL per turn). For large n, P approaches 1.0. Scale by 25 to reduce state space. Use memoization to avoid redundant calculations. When n > ~4800, return 1.0 directly (error < 10^-6). Time: O(n^2/625), Space: O(n^2/625) TutorialsPoint - Soup Servings | Mathematical Optimization Approach
Asked in
Google 15 Microsoft 12
12.5K Views
Medium Frequency
~25 min Avg. Time
485 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen