Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

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.

Leetcode

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: @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

The time complexity is O(C2)O(C^2)O(C2), and the space complexity is O(C2)O(C^2)O(C2). The space complexity is O(C2)O(C^2)O(C2).

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.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy