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(nis an integer).- Return the answer as a Python
float. Results within10^-6relative error of the exact mathematical expectation are accepted.
Step-by-step walkthrough
Understand the rules and stopping condition
The jar begins with
nwhole tablets and0half-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
wholedecreases by1andhalfincreases by1. - Draw a half-tablet: you swallow it completely, so
wholestays the same andhalfdecreases by1.
As soon as
whole == 0, the process stops immediately (any half-tablets still inside the jar are left untouched). Let's warm up by tracingn = 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)- Draw a whole tablet: you swallow half and return the other half to the jar, so
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 to2n - 1days with two branches on almost every day, the number of possible histories grows exponentially (2^nand worse), which is impossible to enumerate forn = 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
wholewhole tablets andhalfhalf-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.Write the recurrence from one day's draw
Define
E(whole, half)as the expected number of additional days needed to reach0whole tablets starting fromwholewhole tablets andhalfhalf-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 >= 0Now suppose
whole >= 1. There aretotal_pills = whole + halfphysical pieces in the jar: - With probabilitywhole / total_pills, today's draw is a whole tablet, moving the jar to(whole - 1, half + 1). - With probabilityhalf / total_pills, today's draw is a half-tablet, moving the jar to(whole, half - 1)(this branch only exists whenhalf > 0).Today itself always costs
1.0day, 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 keepswholefixed and strictly decreaseshalf. Because we never revisit an earlier state, we can compute everyE(whole, half)in a single pass without solving simultaneous equations.Bound the reachable states and choose the table fill order
How large can
halfever get when we start from(n, 0)? Look at the sumwhole + 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 decreaseswhole + halfby1.Therefore, every reachable state satisfies
whole + half <= n, meaninghalfnever exceedsmax_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)E(whole, half)needsE(whole - 1, half + 1)from the previous row (whole - 1). Note that rowwhole - 1has columns0 .. n - whole + 1, sohalf + 1is guaranteed to exist!- When
half > 0,E(whole, half)also needsE(whole, half - 1)from the left neighbor in the current row.
So we fill rows from
whole = 1up ton, and inside each row we sweephalffrom0up ton - whole. Because rowwholeonly ever looks at rowwhole - 1, we only need two 1D lists (prev_rowandcurr_row) instead of a 2D table.Implement the row-by-row dynamic programming loop
Let's translate the two-row sweep directly into clean Python. Starting
prev_rowas[0.0] * (n + 1)represents rowwhole = 0, whereE(0, half) = 0.0for allhalffrom0ton.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: whenhalf == 0, there are no half-tablets to draw, and skipping that branch also avoids readingcurr_row[-1](which in Python would silently wrap around to the end ofcurr_row!).Trace Example 1 (`n = 3`) through the table
Let's watch every row shrink by one element as
wholegrows from0to3: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 = 6producesE(6, 0) = 191 / 20 = 9.55, matching Example 2!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 eachwholefrom1ton, we loophalffrom0ton - whole. Summing those row lengths givesn + (n - 1) + ... + 1 = n * (n + 1) / 2states (about500,500states at the maximumn = 1000), and each state performs a constant number of arithmetic operations. - Space:
O(n). Because computing rowwholeonly reads values from rowwhole - 1and earlier entries of rowwhole, we keep just two 1D lists (prev_rowandcurr_row) of length at mostn + 1rather than allocating a fulln x nmatrix.
Edge cases
n = 1(minimum input): Day 1 draws the single whole tablet with probability1.0, leaving0whole tablets and1half-tablet. The process stops immediately and returns1.0as afloat(not integer1).- 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
0additional days becauseE(0, half) = 0.0. half == 0column: When no half-tablets sit in the jar, only the whole-tablet branch runs (if half > 0skips the half-tablet branch and avoids negative list indexingcurr_row[-1]).- Floating-point stability at
n = 1000: Every term added in the recurrence is positive (1.0plus positive weighted averages), so there is zero catastrophic cancellation; atn = 1000, IEEE-754 double precision matches exact rational arithmetic to roughly1e-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 thentablets would deterministically require2draws (one to split, one to finish), giving2ninstead of25/6forn = 3and9.55forn = 6. - Using
0.5probability for whole vs. half: Drawing a whole tablet does not happen with probability1/2whenever both types exist; with1whole tablet and9half-tablets in the jar, a whole tablet is chosen with probability1 / 10, i.e.,whole / (whole + half). - Sweeping
halfdownward instead of upward:E(whole, half)depends onE(whole, half - 1)in the same row, sohalfmust run from0upward socurr_row[half - 1]is already computed. - Looping
halfall the way tonin every row: States withwhole + half > nare unreachable from(n, 0), and computingE(whole, n)would try to readprev_row[n + 1]and crash withIndexError.
Alternative approaches
- Closed-form mathematical formula in
O(n)time andO(1)space: As derived in the second follow-up below,expected_days(n)simplifies to2 * n - H_n, whereH_n = 1 + 1/2 + 1/3 + ... + 1/nis then-th harmonic number (the sum of the reciprocals of the firstnpositive integers). SummingH_nwithmath.fsumtakes justnsteps; 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): WritingE(whole, half)recursively visits the exact samen * (n + 1) / 2states, but a chain of draws can go2n - 1calls deep (1999frames atn = 1000), which hits Python's default recursion limit of1000unless 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 towhole + half <= n + k. Simply initializeprev_row = [0.0] * (n + k + 1), runhalfup ton + k - wholein each row, and returnprev_row[k](E(n, k)). By symmetry, each of thekinitial half-tablets sits alongside thenwhole tablets and is drawn before the last whole tablet splits with probabilityn / (n + 1), addingk * 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
nwhole tablets always accounts forndraws. Whenever a whole tablet splits whilejun-split whole tablets remain (jtakes each valuen - 1, n - 2, ..., 0once), consider thej + 1items{new_half, W_1, ..., W_j}: by symmetry, each item has probability1 / (j + 1)of being the very last one touched, sonew_halfgets drawn before the last ofW_1, ..., W_jsplits with probability1 - 1 / (j + 1). Summingn + sum_{m=1..n} (1 - 1/m)yields2n - (1 + 1/2 + ... + 1/n) = 2n - H_n(1,2.5,25/6,71/12, ...,9.55atn = 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 probability1 - pand to(whole - 1, half)with probabilityp(discarded without returning a half). Every transition still decreaseswholeorhalf, so the same loop order works after replacingprev_row[half + 1]with(1 - p) * prev_row[half + 1] + p * prev_row[half], lowering the expected turn count because fractionpof whole tablets never generate a half-tablet.
Follow-up questions
- What if the container starts with both n whole tablets and k pre-existing half tablets?
- Is there an O(n)-time closed-form mathematical formula that avoids building the dynamic programming table?
- 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?
Similar questions
- Balance Equalization Transfers and Flat Map Design
- Even Integer Redistribution and Flat Map Iterators
- Bagging, Random Forests, Boosting, and the Bias-Variance Trade-off
- Lock-Free Background C++ Logger with Deferred Formatting
- Raw vs. Smart Pointers in Modern C++
- Negative Return Skewness and Black-Scholes Call Pricing Terms
More Qube Research & Technologies interview questions
- Bagging, Random Forests, Boosting, and the Bias-Variance Trade-off Hard
- Lock-Free Background C++ Logger with Deferred Formatting Hard
- Raw vs. Smart Pointers in Modern C++ Hard Pro
- Negative Return Skewness and Black-Scholes Call Pricing Terms Hard Pro
- Build and Cross-Validate a k-NN Classifier Hard Pro
- Balance Equalization Transfers and Flat Map Design Medium Pro
- Even Integer Redistribution and Flat Map Iterators Medium Pro