Expected Turns Until Zero Whole Tablets

Hard · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

A medicine jar initially contains n intact whole tablets and 0 half-tablets. Once per day, you reach in without looking and draw a single piece uniformly at random from all individual pieces currently inside the jar (so every whole tablet and every half-tablet present has the exact same chance of being chosen):

  • Whole tablet drawn: You split it in two, swallow one half right away, and drop the remaining half back into the jar.
  • Half-tablet drawn: You swallow that half completely, removing it from the jar.

You stop immediately at the end of the day on which the last remaining whole tablet is drawn and split — any half-tablets still sitting in the jar afterward are ignored.

Implement expected_days(n) to return, as a floating-point number, the expected total number of daily draws required until 0 whole tablets remain in the jar.

Examples

Example 1

Input:  n = 3
Output: 4.166666666666667

Day 1 is guaranteed to pick one of the 3 whole tablets, leaving 2 whole tablets and 1 half-tablet (3 pieces total). On Day 2: - With probability 2/3, you draw another whole tablet (reaching 1 whole, 2 halves, which requires 2.0 additional expected days). - With probability 1/3, you draw the half-tablet (reaching 2 wholes, 0 halves, which requires 2.5 additional expected days).

Combining Day 1 with Day 2 gives 1 + (1 + (2/3) * 2.0 + (1/3) * 2.5) = 25 / 6 ≈ 4.166666666666667.

Example 2

Input:  n = 6
Output: 9.55

Starting from 6 whole tablets and 0 half-tablets, evaluating the state transitions down to 0 whole tablets produces an exact expectation of 191 / 20 = 9.55 days.

Constraints

  • 1 <= n <= 1000 (n is an integer).
  • Return the answer as a Python float. Results within 10^-6 relative error of the exact mathematical expectation are accepted.

Step-by-step walkthrough

  1. Understand the rules and stopping condition

    The jar begins with n whole tablets and 0 half-tablets (1 <= n <= 1000). On each day, every individual piece currently inside the jar — whether whole or half — is equally likely to be drawn:

    • Draw a whole tablet: you swallow half and return the other half to the jar, so whole decreases by 1 and half increases by 1.
    • Draw a half-tablet: you swallow it completely, so whole stays the same and half decreases by 1.

    As soon as whole == 0, the process stops immediately (any half-tablets still inside the jar are left untouched). Let's warm up by tracing n = 1, n = 2, and Example 1 (n = 3) by hand:

    n = 1:
      Start (1 whole, 0 half)
       └─ Day 1 (prob 1): draw whole -> (0 whole, 1 half) -> STOP! (1 day)
      Expected days = 1.0
    
    n = 2:
      Start (2 whole, 0 half)
       └─ Day 1 (prob 1): draw whole -> (1 whole, 1 half)
           ├─ Day 2 (prob 1/2): draw whole -> (0 whole, 2 half) -> STOP! (2 days total)
           └─ Day 2 (prob 1/2): draw half  -> (1 whole, 0 half)
               └─ Day 3 (prob 1): draw whole -> (0 whole, 1 half) -> STOP! (3 days total)
      Expected days = 0.5 * 2 + 0.5 * 3 = 2.5
    
    n = 3 (Example 1):
      Start (3 whole, 0 half) -> Day 1 forces (2 whole, 1 half), then:
        prob 2/3 -> (1 whole, 2 half) [2.0 more days], prob 1/3 -> (2 whole, 0 half) [2.5 more days]
      Expected days = 1 + (1 + (2/3) * 2.0 + (1/3) * 2.5) = 25/6 (~4.1667)
    
  2. Why brute force and random simulation fall short

    A brute-force tree search branches on every day's draw until whole == 0. Because a run can last up to 2n - 1 days with two branches on almost every day, the number of possible histories grows exponentially (2^n and worse), which is impossible to enumerate for n = 1000.

    Running thousands of random trials and averaging them fails for a different reason: random simulation error shrinks slowly at the rate 1 / sqrt(trials). Hitting the judge's 6-digit precision reliably would take trillions of simulated days.

    The rescue is that all whole tablets are indistinguishable from one another, and all half-tablets are indistinguishable from one another. Once the jar holds whole whole tablets and half half-tablets, the expected number of remaining days depends only on the pair (whole, half) — not on the sequence of draws that got us there. Merging identical states turns an exponential tree into a compact grid of counts.

  3. Write the recurrence from one day's draw

    Define E(whole, half) as the expected number of additional days needed to reach 0 whole tablets starting from whole whole tablets and half half-tablets.

    First, handle the stopping case: if whole == 0, zero whole tablets remain, so zero extra days are needed:

    E(0, half) = 0.0    for every half >= 0
    

    Now suppose whole >= 1. There are total_pills = whole + half physical pieces in the jar: - With probability whole / total_pills, today's draw is a whole tablet, moving the jar to (whole - 1, half + 1). - With probability half / total_pills, today's draw is a half-tablet, moving the jar to (whole, half - 1) (this branch only exists when half > 0).

    Today itself always costs 1.0 day, and after today's draw we add the probability-weighted average of the expected remaining days from whichever state we land in:

    E(whole, half) = 1.0
                   + (whole / (whole + half)) * E(whole - 1, half + 1)
                   + (half  / (whole + half)) * E(whole,     half - 1)
    

    Notice there are no cycles: every transition either strictly decreases whole, or keeps whole fixed and strictly decreases half. Because we never revisit an earlier state, we can compute every E(whole, half) in a single pass without solving simultaneous equations.

  4. Bound the reachable states and choose the table fill order

    How large can half ever get when we start from (n, 0)? Look at the sum whole + half: - Initially, whole + half = n + 0 = n. - Splitting a whole tablet changes (whole, half) to (whole - 1, half + 1), so (whole - 1) + (half + 1) = whole + half (unchanged). - Swallowing a half-tablet changes (whole, half) to (whole, half - 1), which decreases whole + half by 1.

    Therefore, every reachable state satisfies whole + half <= n, meaning half never exceeds max_half = n - whole! That cuts the table in half into a triangle and prevents reading past the end of a row.

    Let's check which neighbors E(whole, half) reads:

    Row whole - 1 (prev_row):   ...   E(whole - 1, half)    E(whole - 1, half + 1)
                                                                  ^
                                                                  |  (whole tablet drawn)
    Row whole     (curr_row):   ...   E(whole, half - 1) -> E(whole, half)
                                        (half-tablet drawn)
    
    1. E(whole, half) needs E(whole - 1, half + 1) from the previous row (whole - 1). Note that row whole - 1 has columns 0 .. n - whole + 1, so half + 1 is guaranteed to exist!
    2. When half > 0, E(whole, half) also needs E(whole, half - 1) from the left neighbor in the current row.

    So we fill rows from whole = 1 up to n, and inside each row we sweep half from 0 up to n - whole. Because row whole only ever looks at row whole - 1, we only need two 1D lists (prev_row and curr_row) instead of a 2D table.

  5. Implement the row-by-row dynamic programming loop

    Let's translate the two-row sweep directly into clean Python. Starting prev_row as [0.0] * (n + 1) represents row whole = 0, where E(0, half) = 0.0 for all half from 0 to n.

    def expected_days(n: int) -> float:
        # DP state: E(whole, half) is the expected remaining days until 0 whole pills remain.
        # Base case whole == 0: 0 whole pills are left, so 0.0 additional days are needed.
        # prev_row[half] stores E(whole - 1, half), initialized for whole = 0 (half = 0..n).
        prev_row = [0.0] * (n + 1)
    
        # Starting from (n, 0), every reachable state satisfies whole + half <= n,
        # because breaking a whole pill keeps whole + half unchanged and eating a half reduces it.
        for whole in range(1, n + 1):
            max_half = n - whole
            # curr_row[half] will store E(whole, half) for half = 0..max_half.
            curr_row = [0.0] * (max_half + 1)
    
            # Sweep `half` upward from 0 so curr_row[half - 1] is already filled when needed.
            for half in range(max_half + 1):
                total_pills = whole + half
    
                # Whole pill drawn (prob whole / total_pills): 1 fewer whole, 1 more half.
                # prev_row has length max_half + 2, so index half + 1 is always in bounds.
                whole_prob = whole / total_pills
                days = 1.0 + whole_prob * prev_row[half + 1]
    
                # Half pill drawn (prob half / total_pills): it is eaten, leaving half - 1.
                if half > 0:
                    half_prob = half / total_pills
                    days += half_prob * curr_row[half - 1]
    
                curr_row[half] = days
    
            prev_row = curr_row
    
        # At whole == n, max_half == 0, so prev_row[0] holds E(n, 0).
        return prev_row[0]
    

    Notice the if half > 0: guard: when half == 0, there are no half-tablets to draw, and skipping that branch also avoids reading curr_row[-1] (which in Python would silently wrap around to the end of curr_row!).

  6. Trace Example 1 (`n = 3`) through the table

    Let's watch every row shrink by one element as whole grows from 0 to 3:

    Start (whole = 0):
      prev_row = [0.0, 0.0, 0.0, 0.0]              # E(0, 0..3) = 0
    
    whole = 1 (max_half = 2):
      half = 0: 1 + (1/1) * prev_row[1]                  = 1 + 0             = 1.0
      half = 1: 1 + (1/2) * prev_row[2] + (1/2) * 1.0    = 1 + 0 + 0.5       = 1.5
      half = 2: 1 + (1/3) * prev_row[3] + (2/3) * 1.5    = 1 + 0 + 1.0       = 2.0
      curr_row = [1.0, 1.5, 2.0]
    
    whole = 2 (max_half = 1):
      half = 0: 1 + (2/2) * prev_row[1]                  = 1 + 1.5           = 2.5
      half = 1: 1 + (2/3) * prev_row[2] + (1/3) * 2.5    = 1 + 4/3 + 5/6     = 19/6 (~3.1667)
      curr_row = [2.5, 3.1666666666666665]
    
    whole = 3 (max_half = 0):
      half = 0: 1 + (3/3) * prev_row[1]                  = 1 + 19/6          = 25/6 (~4.1667)
      curr_row = [4.166666666666667]
    

    Continuing three rows further to whole = 6 produces E(6, 0) = 191 / 20 = 9.55, matching Example 2!

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def expected_days(n: int) -> float:
        # DP state: E(whole, half) is the expected remaining days until 0 whole pills remain.
        # Base case whole == 0: 0 whole pills are left, so 0.0 additional days are needed.
        # prev_row[half] stores E(whole - 1, half), initialized for whole = 0 (half = 0..n).
        prev_row = [0.0] * (n + 1)
    
        # Starting from (n, 0), every reachable state satisfies whole + half <= n,
        # because breaking a whole pill keeps whole + half unchanged and eating a half reduces it.
        for whole in range(1, n + 1):
            max_half = n - whole
            # curr_row[half] will store E(whole, half) for half = 0..max_half.
            curr_row = [0.0] * (max_half + 1)
    
            # Sweep `half` upward from 0 so curr_row[half - 1] is already filled when needed.
            for half in range(max_half + 1):
                total_pills = whole + half
    
                # Whole pill drawn (prob whole / total_pills): 1 fewer whole, 1 more half.
                # prev_row has length max_half + 2, so index half + 1 is always in bounds.
                whole_prob = whole / total_pills
                days = 1.0 + whole_prob * prev_row[half + 1]
    
                # Half pill drawn (prob half / total_pills): it is eaten, leaving half - 1.
                if half > 0:
                    half_prob = half / total_pills
                    days += half_prob * curr_row[half - 1]
    
                curr_row[half] = days
    
            prev_row = curr_row
    
        # At whole == n, max_half == 0, so prev_row[0] holds E(n, 0).
        return prev_row[0]
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine reaching blindfolded into a jar of candies every morning: whole candies get snapped in half (you eat one half and toss the other half back in), half candies get eaten right away, and you stop the instant the last whole candy is snapped. All whole tablets feel identical to your hand, and all half-tablets feel identical too, so your expected value (the long-run average number of remaining days weighted by each outcome's probability) depends only on two counts: (whole, half) — how many whole tablets and how many half-tablets sit in the jar right now. We compute this with dynamic programming (a technique that avoids repeating work by solving the smallest states first and storing their answers in a table so larger states can look them up in one step).

Why do more obvious approaches fail? Tracing every possible sequence of daily draws branches twice on almost every day for up to 2n - 1 days, creating an exponential number of histories that would never finish even for n = 50. On the other hand, Monte Carlo simulation (estimating an average by running thousands of random trials with a random number generator) has random noise proportional to 1 / sqrt(trials), so getting 6 digits of accuracy reliably would require trillions of trials instead of exact arithmetic.

Instead, we apply the law of total expectation (computing an overall average by taking 1 day for today plus the probability-weighted average of tomorrow's two possible states) from the bottom up. Here is the exact step-by-step trace for Example 1 (n = 3):

Base row (whole = 0):
  E(0, 0) = 0.0,  E(0, 1) = 0.0,  E(0, 2) = 0.0,  E(0, 3) = 0.0

Row whole = 1 (half = 0..2):
  E(1, 0) = 1.0 + (1/1) * E(0, 1)                     = 1.0
  E(1, 1) = 1.0 + (1/2) * E(0, 2) + (1/2) * E(1, 0)   = 1.5
  E(1, 2) = 1.0 + (1/3) * E(0, 3) + (2/3) * E(1, 1)   = 2.0

Row whole = 2 (half = 0..1):
  E(2, 0) = 1.0 + (2/2) * E(1, 1)                     = 2.5
  E(2, 1) = 1.0 + (2/3) * E(1, 2) + (1/3) * E(2, 0)   = 19/6 (~3.1667)

Row whole = 3 (half = 0):
  E(3, 0) = 1.0 + (3/3) * E(2, 1)                     = 25/6 (~4.1667)

Complexity

  • Time: O(n^2). For each whole from 1 to n, we loop half from 0 to n - whole. Summing those row lengths gives n + (n - 1) + ... + 1 = n * (n + 1) / 2 states (about 500,500 states at the maximum n = 1000), and each state performs a constant number of arithmetic operations.
  • Space: O(n). Because computing row whole only reads values from row whole - 1 and earlier entries of row whole, we keep just two 1D lists (prev_row and curr_row) of length at most n + 1 rather than allocating a full n x n matrix.

Edge cases

  • n = 1 (minimum input): Day 1 draws the single whole tablet with probability 1.0, leaving 0 whole tablets and 1 half-tablet. The process stops immediately and returns 1.0 as a float (not integer 1).
  • Leftover half-tablets at the end: When the last whole tablet splits, the jar still holds at least one half-tablet (the half just returned, plus any earlier uneaten halves). Those leftover halves cost 0 additional days because E(0, half) = 0.0.
  • half == 0 column: When no half-tablets sit in the jar, only the whole-tablet branch runs (if half > 0 skips the half-tablet branch and avoids negative list indexing curr_row[-1]).
  • Floating-point stability at n = 1000: Every term added in the recurrence is positive (1.0 plus positive weighted averages), so there is zero catastrophic cancellation; at n = 1000, IEEE-754 double precision matches exact rational arithmetic to roughly 1e-11.

Common mistakes

  • Stopping when the jar is completely empty (whole == 0 and half == 0): If you kept drawing until every half-tablet was swallowed too, each of the n tablets would deterministically require 2 draws (one to split, one to finish), giving 2n instead of 25/6 for n = 3 and 9.55 for n = 6.
  • Using 0.5 probability for whole vs. half: Drawing a whole tablet does not happen with probability 1/2 whenever both types exist; with 1 whole tablet and 9 half-tablets in the jar, a whole tablet is chosen with probability 1 / 10, i.e., whole / (whole + half).
  • Sweeping half downward instead of upward: E(whole, half) depends on E(whole, half - 1) in the same row, so half must run from 0 upward so curr_row[half - 1] is already computed.
  • Looping half all the way to n in every row: States with whole + half > n are unreachable from (n, 0), and computing E(whole, n) would try to read prev_row[n + 1] and crash with IndexError.

Alternative approaches

  • Closed-form mathematical formula in O(n) time and O(1) space: As derived in the second follow-up below, expected_days(n) simplifies to 2 * n - H_n, where H_n = 1 + 1/2 + 1/3 + ... + 1/n is the n-th harmonic number (the sum of the reciprocals of the first n positive integers). Summing H_n with math.fsum takes just n steps; the dynamic programming table remains a great primary interview solution because it adapts effortlessly when transition rules change.
  • Top-down recursion with memoization (@functools.lru_cache): Writing E(whole, half) recursively visits the exact same n * (n + 1) / 2 states, but a chain of draws can go 2n - 1 calls deep (1999 frames at n = 1000), which hits Python's default recursion limit of 1000 unless raised. Bottom-up iteration avoids recursion limits and function-call overhead completely.

Follow-up questions

  • What if the container starts with both n whole tablets and k pre-existing half tablets? Starting from (n, k) instead of (n, 0) keeps the exact same recurrence while expanding the reachable sum invariant to whole + half <= n + k. Simply initialize prev_row = [0.0] * (n + k + 1), run half up to n + k - whole in each row, and return prev_row[k] (E(n, k)). By symmetry, each of the k initial half-tablets sits alongside the n whole tablets and is drawn before the last whole tablet splits with probability n / (n + 1), adding k * n / (n + 1) expected days in closed form.
  • Is there an O(n)-time closed-form mathematical formula that avoids building the dynamic programming table? Yes, via linearity of expectation (the rule that the expected sum of random variables equals the sum of their individual expectations, even when they are dependent). Splitting all n whole tablets always accounts for n draws. Whenever a whole tablet splits while j un-split whole tablets remain (j takes each value n - 1, n - 2, ..., 0 once), consider the j + 1 items {new_half, W_1, ..., W_j}: by symmetry, each item has probability 1 / (j + 1) of being the very last one touched, so new_half gets drawn before the last of W_1, ..., W_j splits with probability 1 - 1 / (j + 1). Summing n + sum_{m=1..n} (1 - 1/m) yields 2n - (1 + 1/2 + ... + 1/n) = 2n - H_n (1, 2.5, 25/6, 71/12, ..., 9.55 at n = 6).
  • How does the recurrence change if every drawn piece has probability p (for instance, p = 0.1) of slipping onto the floor and being discarded unused? Assuming a dropped piece still consumes that day's draw (clarify with your interviewer whether you wait until tomorrow or re-draw immediately), dropping a half-tablet transitions to (whole, half - 1) just like swallowing it, whereas drawing a whole tablet transitions to (whole - 1, half + 1) with probability 1 - p and to (whole - 1, half) with probability p (discarded without returning a half). Every transition still decreases whole or half, so the same loop order works after replacing prev_row[half + 1] with (1 - p) * prev_row[half + 1] + p * prev_row[half], lowering the expected turn count because fraction p of whole tablets never generate a half-tablet.

Follow-up questions

Similar questions

More Qube Research & Technologies interview questions

All 8 Qube Research & Technologies questions →