1451. Ruin or Riches Odds

Medium3.5 points estimatedProbabilityMaths

A gambler holds start tokens and plays rounds of a coin game. In each round the gambler wins one token with probability p and loses one token with probability 1 - p, independently of earlier rounds. Play stops the moment the gambler has 0 tokens (ruin) or goal tokens (riches).

Return the probability, as a double, that play ends with goal tokens. Answers within 1e-6 are accepted. The value of p is given with at most four digits after the decimal point; when p is exactly one half the answer is simply start / goal. Evaluate the closed form in a stable way so that no power overflows; O(1) arithmetic with fast powers is enough.

Example 1

Input:
start = 1, goal = 2, p = 0.5
Output:
0.5
Explanation:
With a fair coin the chance of reaching the goal is start / goal = 1/2.

Example 2

Input:
start = 2, goal = 5, p = 0.5
Output:
0.4
Explanation:
A fair coin gives start / goal = 2/5 = 0.4.

Example 3

Input:
start = 3, goal = 4, p = 0.75
Output:
0.975
Explanation:
With a favourable coin the closed form with ratio 1/3 gives exactly 0.975.

Constraints

1 ≤ goal ≤ 1000

0 ≤ start ≤ goal

0.01 ≤ p ≤ 0.99, with at most four digits after the decimal point

How this problem is judged

Answers
Numbers are accepted within a tolerance of 1.0E-6: |answer - expected| <= 1.0E-6 x max(1, |expected|).
Tolerance
0.000001

Expected complexity

Time
O(log goal)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…