KatInterview

Gambler's Ruin: Success Probability and Duration Score

Math & Bit ManipulationAuto-graded · 21 test cases
MediumAuto-gradedMath & Bit Manipulationprobabilitymarkov-chainclosed-form

Last 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_prob they gain one coin.
  • With probability 1 - win_prob they 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:

  1. Success probability. The probability that the player reaches target before reaching 0.
  2. 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 is 0.0. This check comes first, even if target is also 0.
  • Otherwise, if start == target, the probability is 1.0.
  • Otherwise, if win_prob == 0.5, the probability is start / 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 <= target
  • 0 < win_prob < 1
  • target can be large enough that computing r^target directly 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 start is small and win_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.