KatInterview

Chance a Daily +/- Walk Ends Below Zero

Math & Bit ManipulationAuto-graded · 21 test cases
MediumAuto-gradedMath & Bit Manipulationprobabilitybinomialnumerical-stability

Last updated

Model a price as a two-step random walk, reduce it to a binomial lower tail with a strict cutoff, and sum that tail in a numerically stable way.

A quantity starts at the value s. For each of n consecutive days, independently of the other days, it goes up by x with probability p, or down by x with probability 1 - p, where x > 0.

Return the probability that the value after all n days is strictly less than 0.

Only the final value matters. The path taken, and whether it dipped below zero earlier, is irrelevant. A final value of exactly 0 does not count.

Details

  • If n = 0, the value never changes, so the answer is 1.0 if s < 0 and 0.0 otherwise.
  • If the outcome is impossible, return 0.0. If it is certain, return 1.0.
  • The result is a float. It is compared against the expected value with a small floating-point tolerance, so it must be accurate, not just approximate. Large n must not cause overflow, underflow, or nan.
  • Be careful with the strict inequality at the boundary, where some number of up-days leaves the value at exactly 0.

Input

  • s: the starting value (float, may be negative, zero, or positive)
  • x: the step size (float, x > 0)
  • p: the probability of an up-move on each day (float, 0 <= p <= 1)
  • n: the number of days (integer, n >= 0)

Output

A float in [0, 1]: the probability that the final value is strictly below 0.

Constraints

  • n >= 0, and n may be several thousand, so naive comb(n, k) * p**k * (1-p)**(n-k) in floating point can overflow or underflow
  • x > 0
  • 0 <= p <= 1, including the degenerate values 0 and 1
  • s is any finite real number
  • A solution that runs in O(n) time is acceptable

Examples

Example 1

Input: prob_final_below_zero(10, 2, 0.5, 5)

Output: 0

Example 2

Input: prob_final_below_zero(1, 1, 0.5, 2)

Output: 0.25

Example 3

Input: prob_final_below_zero(5, 3, 0.25, 4)

Output: 0.7382812499999992

Example 4

Input: prob_final_below_zero(0, 2, 0.5, 3)

Output: 0.5000000000000004

Hints

Hint 1

Let K be the number of up-days. The final value equals s + x*(2K - n), so the whole problem depends only on K, which is Binomial(n, p).

Hint 2

Solve s + x*(2K - n) < 0 for K. Because K is an integer and equality (final value exactly 0) must be excluded, the largest allowed K is ceil(boundary) - 1, not floor(boundary). Handle cases where no K or every K qualifies.

Hint 3

Do not multiply huge binomial coefficients by tiny powers directly. Compute one term in log space with lgamma, then move to neighboring terms with the ratio recurrence, and use math.fsum. Sum whichever tail is shorter and use 1 minus the other tail if needed.