KatInterview

Gambler's Ruin: Chance of Hitting the Goal Before Bust

Math & Bit ManipulationAuto-graded · 19 test cases
MediumAuto-gradedMath & Bit Manipulationprobabilitygambler's ruinrecurrence

Last updated

Compute the probability that a biased ±1 random walk reaches a target balance before hitting zero, using a recurrence and closed form with careful edge cases.

A player begins with start units of money and repeatedly plays a round of a betting game. In each round, a weighted coin is tossed:

  • With probability p it shows heads, and the player gains exactly 1 unit.
  • With probability 1 - p it shows tails, and the player loses exactly 1 unit.

Rounds are independent, and p never changes. Play stops the moment the player's balance equals 0 (bust) or target (goal).

Write a function that returns the probability that the player reaches target before reaching 0.

Special cases

Apply these rules in this order before using any general formula:

  1. If start <= 0, the player is already bust. Return 0.0.
  2. If start >= target, the goal is already met. Return 1.0.
  3. If p == 0.0, return 0.0.
  4. If p == 1.0, return 1.0.
  5. If p == 0.5, the game is fair. Return start / target.

Otherwise, compute the probability for the general biased case.

Input

  • start: integer, the starting balance.
  • target: integer, the balance at which the player stops and wins.
  • p: float, the probability of winning a single round.

Output

A float: the probability of reaching target before 0.

Constraints

  • start and target are integers.
  • 0.0 <= p <= 1.0.
  • p stays constant during the game.
  • The game ends immediately upon reaching 0 or target.
  • Results are compared as floating-point numbers, so use the standard closed-form expression rather than simulation.

Examples

Example 1

Input: reach_goal_probability(10, 20, 0.6)

Output: 0.9829540725450702

Example 2

Input: reach_goal_probability(10, 20, 0.5)

Output: 0.5

Example 3

Input: reach_goal_probability(3, 10, 0.4)

Output: 0.04191296854803968

Hints

Hint 1

Let f(x) be the chance of success from balance x. Condition on the first round to relate f(x) to f(x+1) and f(x-1), with f(0) = 0 and f(target) = 1.

Hint 2

Rewrite the recurrence in terms of differences f(x+1) - f(x). Each difference is the previous one multiplied by r = (1-p)/p, so the values form a geometric series.

Hint 3

Summing the geometric series and normalizing so that f(target) = 1 gives (1 - r^start) / (1 - r^target). This breaks down when r = 1 (p = 0.5), so handle that case separately with start / target.