Chance a Daily +/- Walk Ends Below Zero
Math & Bit ManipulationAuto-graded · 21 test casesLast 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 is1.0ifs < 0and0.0otherwise. - If the outcome is impossible, return
0.0. If it is certain, return1.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
nmust not cause overflow, underflow, ornan. - 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, andnmay be several thousand, so naivecomb(n, k) * p**k * (1-p)**(n-k)in floating point can overflow or underflowx > 00 <= p <= 1, including the degenerate values0and1sis 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Reduce to a binomial. Let K be the number of up-days. Each day is an independent Bernoulli(p) trial, so K ~ Binomial(n, p). The final value is
s + x*K - x*(n - K) = s + x*(2K - n).
Only K matters, not the order of the moves.
Find the cutoff. Since x > 0, the final value is negative exactly when
K < (n*x - s) / (2*x).
K is an integer and a final value of exactly 0 must be excluded, so the largest valid count is
k_max = ceil((n*x - s) / (2*x)) - 1.
Using ceil(...) - 1 instead of floor(...) matters when the boundary is an integer: that K lands exactly on 0 and must not be counted.
The answer is P(K <= k_max).
Edge cases.
- If
k_max < 0, no outcome is negative, so return0.0. - If
k_max >= n, every outcome is negative, so return1.0. - If
p == 0,K = 0always, and sincek_max >= 0here the answer is1.0. - If
p == 1,K = nalways, and sincek_max < nhere the answer is0.0. n = 0falls out of the general rule:k_max >= 0 = nwhens < 0, giving1.0, andk_max < 0otherwise, giving0.0.
Compute the tail stably. Evaluating comb(n, k) * p**k * (1-p)**(n-k) directly overflows or underflows for large n. Instead:
- Compute a single pmf term in log space using
lgamma,log, andlog1p. - Obtain neighboring terms with the ratio recurrence
pmf(k-1) = pmf(k) * (k / (n-k+1)) * ((1-p)/p)going down, orpmf(k+1) = pmf(k) * ((n-k)/(k+1)) * (p/(1-p))going up. - Add the terms with
math.fsum.
To avoid cancellation and keep the sum short, pick the side by comparing k_max with the mean n*p:
- If
k_max <= n*p, the lower tail is the smaller side. Start atk_maxand sum downward to 0. - Otherwise sum the upper tail from
k_max + 1ton - 1and return1 - upper. The upper tail starts atk_max + 1, whose term is computed in log space, and the loop adds terms forj = k_max + 1, ..., n - 1, so the last termK = nis omitted fromupper(the sum is forK = k_max+1 ... n-1after the recurrence, with the final step adding theK = nterm). In the code the recurrence is appliedn - firsttimes, sotermsincludes everyKfromfirstton.
The result is clamped to [0, 1] to remove tiny rounding drift.
Why it is correct
The event "final value < 0" is exactly the event K <= k_max, and K is binomial. The ratio recurrence reproduces the exact pmf values, and the log-space start avoids overflow and underflow. Summing the shorter tail with fsum keeps the rounding error small.
Complexity
- Time:
O(n)in the worst case, since at most aboutnterms are summed. - Space:
O(n)for the stored terms, which could be reduced toO(1)with a running sum.
Reference solution
import math
def prob_final_below_zero(s: float, x: float, p: float, n: int) -> float:
if n < 0:
raise ValueError("n must be nonnegative")
if x <= 0 or not (0.0 <= p <= 1.0):
raise ValueError("require x > 0 and 0 <= p <= 1")
# With K up-days the final value is s + x * (2*K - n).
# It is negative exactly when K < (n*x - s) / (2*x).
boundary = (n * x - s) / (2.0 * x)
k_max = math.ceil(boundary) - 1 # largest K that still gives a value < 0
if k_max < 0:
return 0.0
if k_max >= n:
return 1.0
if p == 0.0:
return 1.0
if p == 1.0:
return 0.0
# Sum the shorter side of the distribution. Start from one term computed
# in log space and walk to neighbouring terms with a ratio recurrence.
if k_max <= n * p:
k = k_max
log_term = (
math.lgamma(n + 1)
- math.lgamma(k + 1)
- math.lgamma(n - k + 1)
+ k * math.log(p)
+ (n - k) * math.log1p(-p)
)
term = math.exp(log_term)
terms = [term]
for j in range(k, 0, -1):
term *= (j / (n - j + 1)) * ((1.0 - p) / p)
terms.append(term)
return min(1.0, max(0.0, math.fsum(terms)))
first = k_max + 1
k = first
log_term = (
math.lgamma(n + 1)
- math.lgamma(k + 1)
- math.lgamma(n - k + 1)
+ k * math.log(p)
+ (n - k) * math.log1p(-p)
)
term = math.exp(log_term)
terms = [term]
for j in range(first, n):
term *= ((n - j) / (j + 1)) * (p / (1.0 - p))
terms.append(term)
upper = math.fsum(terms)
return min(1.0, max(0.0, 1.0 - upper))