Random Transfer Between Two Queues: Drain Time and Odds
Arrays & HashingAuto-graded · 24 test casesLast updated
Tests ability to model a lazy symmetric random walk as a Markov chain, derive a closed-form hitting-time formula, and compute absorption probabilities analytically.
Problem Description
Two token piles, Pile A and Pile B, together hold exactly n tokens at all times. At the start, Pile A contains k tokens and Pile B contains n − k tokens.
Each round proceeds as follows:
- Pick a source pile uniformly at random from
{A, B}. - Independently pick a destination pile uniformly at random from
{A, B}. - If the two choices differ, move one token from the source pile to the destination pile.
- If the two choices are the same, no token moves — but the round still counts.
The process stops the moment either pile reaches exactly 0 tokens.
You must compute two quantities:
- Expected rounds: the expected number of rounds until one pile is empty, starting from
ktokens in Pile A. - Drain probability: the probability that Pile A drains first (reaches 0 before Pile B does).
Return both values in a dictionary with keys "expected_rounds" and "probability_line_a_empties_first".
Deriving the answers
Step 1 — State space.
Because the total is conserved, the system state is fully described by k, the current number of tokens in Pile A. The state space is {0, 1, …, n}, with 0 and n as absorbing states (Pile A empty and Pile B empty, respectively).
Step 2 — Transition probabilities. Each of the four (source, destination) pairs is equally likely (probability 1/4 each):
| Source → Destination | Probability | Effect on k |
|---|---|---|
| A → B | 1/4 | k − 1 |
| B → A | 1/4 | k + 1 |
| A → A | 1/4 | no change |
| B → B | 1/4 | no change |
So from any interior state 1 ≤ k ≤ n − 1, the walk moves left or right with probability 1/4 each and stays put with probability 1/2. This is a lazy symmetric random walk.
Step 3 — Expected rounds recurrence.
Let E[k] be the expected number of rounds to absorption starting from state k. By first-step analysis:
E[k] = 1 + (1/4) E[k−1] + (1/4) E[k+1] + (1/2) E[k], for 1 ≤ k ≤ n−1
with boundary conditions E[0] = 0 and E[n] = 0.
Rearranging (subtract (1/2)E[k] from both sides, multiply by 4):
E[k+1] − 2E[k] + E[k−1] = −4
Step 4 — Solving the recurrence.
The homogeneous part has solution a + bk; a particular solution for the constant right-hand side is −2k² (verify: −2(k+1)² + 4k² − 2(k−1)² = −4). The general solution is:
E[k] = −2k² + a + bk
Applying E[0] = 0 gives a = 0. Applying E[n] = 0 gives b = 2n. Therefore:
E[k] = 2k(n − k)
The factor of 2 relative to the classic gambler's ruin result k(n − k) comes from the self-loop: the walk only steps half the time, so each effective move costs 2 rounds on average.
Step 5 — Drain probability.
Let p[k] be the probability that Pile A drains first starting from state k. First-step analysis gives:
p[k] = (1/2) p[k−1] + (1/2) p[k+1], with p[0] = 1, p[n] = 0
The self-loop terms cancel exactly, leaving a harmonic equation whose solution is linear in k:
p[k] = (n − k) / n
Pile A is more likely to drain first when it starts with fewer tokens than Pile B.
Edge cases
- When
k = 0, Pile A is already empty:expected_rounds = 0andprobability_line_a_empties_first = 1.0. - When
k = n, Pile B is already empty:expected_rounds = 0andprobability_line_a_empties_first = 0.0. - When
k = n/2(equal piles), the drain probability is exactly 0.5 by symmetry.
Constraints
1 ≤ n ≤ 10^60 ≤ k ≤ n- Both
nandkare integers. - The return value must be a
dictwith exactly the keys"expected_rounds"(integer or float) and"probability_line_a_empties_first"(float).
Examples
Example 1
Input: pile_drain_metrics(13, 6)
Output: {'expected_rounds': 84, 'probability_line_a_empties_first': 0.5384615384615384}
Example 2
Input: pile_drain_metrics(2, 1)
Output: {'expected_rounds': 2, 'probability_line_a_empties_first': 0.5}
Example 3
Input: pile_drain_metrics(10, 0)
Output: {'expected_rounds': 0, 'probability_line_a_empties_first': 1}
Example 4
Input: pile_drain_metrics(10, 10)
Output: {'expected_rounds': 0, 'probability_line_a_empties_first': 0}
Hints
Hint 1
The total number of tokens never changes, so one integer — how many tokens are currently in Pile A — is all you need to track the system state. What does that tell you about the size of the state space?
Hint 2
Write the first-step equation for E[k], then move the E[k] self-loop term to the left side. You should end up with a second-difference equation with a constant right-hand side — a form you can solve exactly with a particular solution of the form ck².
Hint 3
The self-loops affect expected time but not which pile drains first. For the drain probability, the self-loop terms cancel, leaving a linear harmonic equation whose solution you can read off directly from the boundary conditions.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Core insight: one-dimensional state
Because every transfer merely moves a token from one pile to the other, the total n is invariant. The full system state is therefore just k, the number of tokens in Pile A. Pile B always holds n − k. This reduces a two-variable problem to a one-dimensional random walk on {0, 1, …, n} with two absorbing boundaries.
Transition structure
Each round, exactly one of four equally likely (source, destination) pairs is chosen. Two of the four pairs leave k unchanged (self-transfers); one decreases k by 1; one increases it by 1. The result is a lazy symmetric random walk: it moves left or right each with probability 1/4 and stays put with probability 1/2.
Expected rounds
First-step analysis on E[k] gives:
E[k] = 1 + (1/4)E[k−1] + (1/4)E[k+1] + (1/2)E[k]
Isolating the second difference:
E[k+1] − 2E[k] + E[k−1] = −4
This is a linear recurrence with constant coefficients. The homogeneous solution is a + bk; a particular solution is −2k² (since its second difference is exactly −4). Applying E[0] = 0 and E[n] = 0 pins down the constants:
E[k] = 2k(n − k)
The factor of 2 compared to the non-lazy walk k(n − k) makes sense intuitively: the walk only takes an effective step half the time, so reaching a boundary costs twice as many rounds on average.
Drain probability
Let p[k] be the probability that Pile A (state 0) is reached before Pile B (state n). The self-loop terms are equal on both sides of the first-step equation and cancel, leaving:
p[k] = (1/2)p[k−1] + (1/2)p[k+1]
This is the standard harmonic (discrete Laplace) equation. Its solution, subject to p[0] = 1 and p[n] = 0, is simply:
p[k] = (n − k) / n
Self-loops do not affect which boundary is hit — only how long it takes to get there.
Correctness checks
- Both formulas vanish correctly at the boundaries.
E[k]is symmetric underk ↔ n − k(swapping pile labels), as expected.- At
k = n/2(equal piles),p[k] = 1/2by symmetry. - For
n = 13, k = 6:E[6] = 2 · 6 · 7 = 84andp[6] = 7/13 ≈ 0.538. Pile A starts one token smaller, so it has a slightly higher chance of draining first.
Complexity
- Time: O(1) — both formulas are a constant number of arithmetic operations.
- Space: O(1) — no auxiliary data structures needed.
Reference solution
from typing import Dict
def pile_drain_metrics(n: int, k: int) -> Dict[str, float]:
"""
Closed-form solution derived from the lazy symmetric random walk model.
Expected rounds: E[k] = 2k(n - k)
- Comes from solving E[k+1] - 2E[k] + E[k-1] = -4 with E[0]=E[n]=0.
- The factor of 2 vs. the classic gambler's ruin k(n-k) reflects
that the walk only steps with probability 1/2 each round.
Drain probability: p[k] = (n - k) / n
- Self-loops cancel in the first-step equation for absorption
probability, leaving a linear harmonic equation.
- Pile A starts with k tokens, so it is more likely to drain first
whenever k < n/2.
"""
if n < 1 or k < 0 or k > n:
raise ValueError("k must satisfy 0 <= k <= n")
expected_rounds = 2 * k * (n - k)
probability_line_a_empties_first = (n - k) / n
return {
"expected_rounds": expected_rounds,
"probability_line_a_empties_first": probability_line_a_empties_first,
}