KatInterview

Aggressive Wagering: Chance of Hitting the Goal Before Going Broke

Math & Bit ManipulationAuto-graded · 19 test cases
MediumAuto-gradedMath & Bit Manipulationprobabilitymarkov-chainlinear-algebra

Last updated

Model a state-dependent betting strategy as a Markov chain and solve absorption probabilities, including cycles, via a linear system.

A player holds some number of chips and wants to grow the pile to a fixed goal. The player repeatedly places a single bet, and each bet is settled independently.

Betting rule

If the player currently holds x chips (with 0 < x < goal), the wager is the largest amount that is still sensible:

  • It cannot exceed the chips the player holds, x.
  • It cannot exceed the chips still needed to reach the goal, goal - x.

So the wager is min(x, goal - x).

Each bet is won with probability win_prob. A win adds the wagered amount to the pile; a loss removes it. Bets are independent.

Stopping

The game ends as soon as the pile reaches goal chips (success) or 0 chips (ruin). Since the wager never exceeds x or goal - x, the pile always stays between 0 and goal.

Task

Return the probability that the pile reaches goal before it reaches 0.

Edge-case rules:

  • If start >= goal, return 1.0.
  • If start <= 0, return 0.0.

Note that the pile can return to a previously visited value, so a single path-product is not enough; all repeated visits must be accounted for.

Constraints

  • start, goal are integers; goal is small (at most a few dozen).
  • 0 <= win_prob <= 1.
  • Answers are compared as floating-point numbers with a small tolerance.

Examples

Example 1

Input: chance_of_reaching_goal(3, 5, 0.6)

Output: 0.7283531409168081

Hints

Hint 1

Define f(x) as the probability of eventually reaching the goal from x chips, with f(0)=0 and f(goal)=1. Condition on the result of the next bet.

Hint 2

Each non-terminal state gives one linear equation: f(x) = p*f(x+bet) + q*f(x-bet). Because states can repeat, you get a system of equations rather than a simple recursion.

Hint 3

Solve the (goal-1)-variable linear system with Gaussian elimination (partial pivoting), moving the known boundary value f(goal)=1 to the right-hand side.