Gambler's Ruin: Success Probability and Duration Score
Math & Bit ManipulationAuto-graded · 21 test casesLast updated
Compute the chance a random walk hits a target before zero using a closed form, handling the fair case and overflow, and return a fixed duration formula.
Random Walk Between Two Barriers
A player starts with start coins. Each round, they stake one coin:
- With probability
win_probthey gain one coin. - With probability
1 - win_probthey lose one coin.
Rounds are independent. The game stops as soon as the player holds 0 coins (bust) or target coins (goal).
Write a function that returns two numbers, in this order:
- Success probability. The probability that the player reaches
targetbefore reaching0. - Duration score. The value
start * (target - start), returned as a float.
Rules for the two values
Success probability. Let q = 1 - win_prob and r = q / win_prob.
- If
start == 0, the probability is0.0. This check comes first, even iftargetis also0. - Otherwise, if
start == target, the probability is1.0. - Otherwise, if
win_prob == 0.5, the probability isstart / target. - Otherwise, the probability is
(1 - r^start) / (1 - r^target).
Duration score. The second value is always start * (target - start), whatever win_prob is. It is the expected number of rounds in a fair game, but here it is simply a formula applied to every input. Do not adjust it for biased games.
Return a list [probability, duration_score], both as floats. Results are compared with a small numerical tolerance.
Constraints
0 <= start <= target0 < win_prob < 1targetcan be large enough that computingr^targetdirectly overflows or loses precision, so evaluate the formula in a numerically stable way.- The probability must be accurate when it is very small (for example, a tiny result when
startis small andwin_prob < 0.5).
Examples
Example 1
Input: ruin_stats(2, 4, 0.5)
Output: [0.5, 4]
Example 2
Input: ruin_stats(1, 4, 0.25)
Output: [0.02499999999999999, 3]
Example 3
Input: ruin_stats(3, 10, 0.6)
Output: [0.7161223610512709, 21]
Hints
Hint 1
Condition on the first round: P(k) = p*P(k+1) + q*P(k-1) with P(0)=0 and P(target)=1. Solving it gives a geometric-sum closed form in r = q/p.
Hint 2
When win_prob is exactly 0.5 the ratio r equals 1 and the geometric formula becomes 0/0, so use start/target there.
Hint 3
To avoid overflow and cancellation, work with log(r) and use expm1. If r < 1, use -expm1(k*log r). If r > 1, rewrite the ratio with negative exponents once target*log r gets large.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Success probability. Let P(k) be the chance of reaching target before 0 from k coins. Conditioning on the first round gives
P(k) = p*P(k+1) + q*P(k-1) for 0 < k < target, with P(0) = 0 and P(target) = 1.
Rearranging gives p*(P(k+1) - P(k)) = q*(P(k) - P(k-1)). So the successive differences form a geometric sequence with ratio r = q/p. Summing them from 0 gives P(k) = D * (1 + r + ... + r^(k-1)), and the condition P(target) = 1 fixes D.
- If
r != 1, thenP(k) = (1 - r^k) / (1 - r^target). - If
r == 1(the fair game), thenP(k) = k / target.
The boundary values 0 and 1 are handled directly, with the start == 0 check first.
Numerical stability. Computing r^target directly can overflow or lose precision, so the code works with L = log(r).
- If
r < 1(L < 0), every power lies in(0, 1). Using-expm1(k*L)for1 - r^kkeeps full precision even when the result is tiny. - If
r > 1(L > 0), rewrite(r^a - 1)/(r^b - 1)asexpm1(a*L) / expm1(b*L)whileb*L < 700. Beyond that,expm1(b*L)would overflow, so use the equivalent formexp((a-b)*L) * (1 - e^(-aL)) / (1 - e^(-bL)), in which every exponent is non-positive.
Duration score. This is the fixed expression start * (target - start), returned as a float. It is the exact expected duration of the fair game, but this problem applies it to every input.
Why it is correct
The recurrence with its two boundary conditions has a unique solution, and the formulas above satisfy it. The log and expm1 rewrites are algebraically identical to the plain formula and only change how it is evaluated.
Complexity
Time O(1) and space O(1).
Reference solution
import math
from typing import List
def ruin_stats(start: int, target: int, win_prob: float) -> List[float]:
if start == 0:
probability = 0.0
elif start == target:
probability = 1.0
elif win_prob == 0.5:
probability = start / target
else:
lose_prob = 1.0 - win_prob
log_r = math.log(lose_prob / win_prob)
if log_r < 0:
# r < 1: both powers are in (0, 1), so this is safe
num = -math.expm1(start * log_r)
den = -math.expm1(target * log_r)
probability = num / den
else:
# r > 1: avoid overflow of r**target
a = start * log_r
b = target * log_r
if b < 700:
probability = math.expm1(a) / math.expm1(b)
else:
probability = (
math.exp((start - target) * log_r)
* (-math.expm1(-a))
/ (-math.expm1(-b))
)
duration_score = float(start * (target - start))
return [probability, duration_score]