Stopping-Score Cap Probability Under Uniform Draws
Medium · Coding & Algorithms · Machine Learning Engineer · Technical Screen
Problem Statement
Consider a random accumulation process whose running counter begins at 0. Whenever the counter is strictly below threshold, one step adds an integer picked independently and uniformly from {1, 2, ..., max_points}. The instant the counter becomes greater than or equal to threshold, the process halts and no further steps are taken (if threshold == 0, zero steps occur and the counter halts immediately at 0).
Implement
def probability_within_limit(limit: int, threshold: int, max_points: int) -> float:
to compute the probability that the halting value of the counter does not exceed limit. Any floating-point return value within 1e-5 absolute error of the true probability is accepted.
Examples
Example 1
Input: limit = 7, threshold = 1, max_points = 8
Output: 0.875
Walk-through: Starting from 0 < 1, the very first step adds a uniform integer in 1..8, which always reaches at least 1 and halts immediately. Seven of those eight equally likely outcomes (1 through 7) are <= 7, giving 7 / 8 = 0.875.
Example 2
Input: limit = 3, threshold = 2, max_points = 3
Output: 0.88889
Walk-through: Stepping directly to 2 or 3 on the first turn (1/3 chance each) halts inside <= 3. Stepping to 1 (1/3 chance) triggers one more step onto 2, 3, or 4 (1/9 chance each). Only the path 0 -> 1 -> 4 exceeds 3, so the probability is 1 - 1/9 = 8/9 ≈ 0.88889.
Example 3
Input: limit = 4, threshold = 4, max_points = 2
Output: 0.6875
Walk-through: Each step adds 1 or 2 with probability 1/2 while the counter stays below 4. The counter visits 1 with probability 1/2, 2 with probability 3/4, and 3 with probability 5/8. Only 2 (rolling 2) and 3 (rolling 1 or 2, where 1 lands on 4 and 2 overshoots to 5) can end the process, landing on 4 with probability (3/4) * (1/2) + (5/8) * (1/2) = 11/16 = 0.6875.
Constraints
0 <= threshold <= limit <= 10^41 <= max_points <= 10^4
Step-by-step walkthrough
Understand the process and the possible halting scores
The counter starts at
0. Whenever the current score is strictly belowthreshold, we roll a fairmax_points-sided die (adding a uniform integer from1tomax_points). The instant the score reachesthresholdor higher, the process halts immediately. We want the probability that this halting score is at mostlimit.Picture the non-negative integers split into two regions:
Active stepping zone (< threshold) Halting zone (>= threshold) +-----------------------------------+-----------------------------------------+ 0, 1, 2, ..., threshold - 1 | threshold, ..., (threshold - 1) + W keep rolling again halt immediately(Here
Wdenotesmax_points.) Two bounds follow right away:- Every halting score is at least
threshold, since we never stop earlier. - Every halting score is at most
(threshold - 1) + max_points, since the final step starts atthreshold - 1or below and adds at mostmax_points.
- Every halting score is at least
Define the state: probability of visiting each score
We can compute exact probabilities with dynamic programming — ordering subproblems from smallest to largest so each state is computed once from earlier states.
Let
reach_prob[score]be the probability that the running counter ever lands onscoreduring a run:- Every run begins at
0, soreach_prob[0] = 1.0. - Because every step adds at least
1, the counter strictly increases and can touch any integer at most once per run. Reachingscorefrom predecessorprev = 1and reachingscorefromprev = 2are mutually exclusive events (two events that can never occur in the same run), so their probabilities simply add! - Which predecessors
prevcan jump straight toscorein a single step?prevmust lie within one step's reach:score - max_points <= prev <= score - 1(withprev >= 0).- The counter must still have been active at
prev, meaningprev < threshold. - From
prev, we must roll the exact gapscore - prev, which happens with probability1 / max_points.
Combining those three conditions gives the recurrence:
reach_prob[score] = (1 / max_points) * sum of reach_prob[prev] over max(0, score - max_points) <= prev <= score - 1 with prev < thresholdFor any
score >= threshold, touchingscorehalts the run immediately, soreach_prob[score]equals the exact probability of finishing atscore. Summingreach_prob[score]acrossthreshold <= score <= limityields our answer.- Every run begins at
Why naive summation and random trials fall short
Summing up to
max_pointspredecessors from scratch for everyscoretakesO(limit * max_points)operations. Atlimit = 10^4andmax_points = 10^4, that performs tens of millions of redundant additions over heavily overlapping intervals.Simulating random runs (Monte Carlo simulation — estimating a probability by repeating random trials and measuring the empirical win rate) is far worse: sampling noise decays as
1 / sqrt(trials), requiring billions of simulated runs to guarantee1e-5accuracy.Key idea: maintain a sliding window of active scores
Compare the active predecessors summed for consecutive scores when
max_points = 3andthreshold = 4:For score = 3: sum active prev in [0, 1, 2] For score = 4: sum active prev in [1, 2, 3] (entered 3, evicted 0) For score = 5: sum active prev in [2, 3] (4 >= threshold, NOT added; evicted 1)Advancing from
scoretoscore + 1changes the predecessor sum in at most two places! A single variablewindow_sumupdates inO(1)time per score:- Set
reach_prob[score] = window_sum / max_points. - If
score < threshold, the process remains active atscore, so addreach_prob[score]towindow_sum. Otherwise (score >= threshold), the process halts atscore, so addreach_prob[score]towithin_limit_probinstead (never towindow_sum). - Before advancing to
score + 1, inspectleaving_score = score - max_points. Whenever0 <= leaving_score < threshold, subtractreach_prob[leaving_score]fromwindow_sumbecauseleaving_scorecan no longer reachscore + 1in one step.
- Set
Handle the boundary cases up front
Three O(1) guards dispose of corner cases before the loop:
limit < threshold: halting belowthresholdis impossible, so return0.0.threshold == 0: the counter starts at0 >= threshold, takes zero steps, and halts at0 <= limit, so return1.0. Returning early is critical: otherwisewindow_sum = 1.0would treat0as an active score!limit >= (threshold - 1) + max_points: even the largest possible halting score is<= limit, so return1.0immediately.
# Phase 1: Handle immediate boundary cases before running dynamic programming. if limit < threshold: return 0.0 if threshold == 0: return 1.0 max_possible_final = (threshold - 1) + max_points if limit >= max_possible_final: return 1.0Code the sliding-window loop
We allocate
reach_probonly through indexlimit, since scores pastlimitneither contribute towithin_limit_probnor feed smaller scores. Note that the eviction guard checks0 <= leaving_score < thresholdso we only subtract valid scores that were actually added intowindow_sum.# reach_prob[score]: probability that the running total ever lands on 'score' reach_prob = [0.0] * (limit + 1) reach_prob[0] = 1.0 window_sum = 1.0 within_limit_prob = 0.0 # Phase 2: Sweep score from 1 to limit, updating the active window in O(1) per step. for score in range(1, limit + 1): reach_prob[score] = window_sum / max_points if score < threshold: window_sum += reach_prob[score] else: within_limit_prob += reach_prob[score] leaving_score = score - max_points if 0 <= leaving_score < threshold: window_sum -= reach_prob[leaving_score] return within_limit_probTrace Example 3 step by step
Trace
limit = 4,threshold = 4,max_points = 2. Heremax_possible_final = (4 - 1) + 2 = 5, and4 < 5, so we sweepscore = 1..4(watch howleaving_scoreevicts0and1along the way):score window_sum (before) reach_prob[score] action at score evict (score - 2) window_sum (after) ----- ------------------- ----------------- ------------------------ ----------------- ------------------ start - reach_prob[0]=1 0 < 4: active - 1 1 1 1 / 2 = 1/2 1 < 4: add to window -1 (ignore) 1 + 1/2 = 3/2 2 3/2 (3/2) / 2 = 3/4 2 < 4: add to window 0 (< 4, subtract) 3/2 + 3/4 - 1 = 5/4 3 5/4 (5/4) / 2 = 5/8 3 < 4: add to window 1 (< 4, subtract) 5/4 + 5/8 - 1/2 = 11/8 4 11/8 (11/8) / 2 = 11/16 4 >= 4: halt! ans=11/16 2 (< 4, subtract) 11/8 - 3/4 = 5/8The loop returns
within_limit_prob = 11/16 = 0.6875, matching Example 3. Notice that the leftoverwindow_sum = 5/8corresponds toreach_prob[5] = (5/8) / 2 = 5/16, and11/16 + 5/16 = 1!Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def probability_within_limit(limit: int, threshold: int, max_points: int) -> float: # Phase 1: Handle immediate boundary cases before running dynamic programming. # Because the player only stops at 'threshold' or higher, ending below it is impossible. if limit < threshold: return 0.0 # When threshold == 0, the player starts at 0 >= threshold and never draws; # returning early prevents the loop below from treating 0 as an active drawing score. if threshold == 0: return 1.0 # The final draw starts from at most (threshold - 1) and adds at most max_points, # so no game can ever end above max_possible_final. max_possible_final = (threshold - 1) + max_points if limit >= max_possible_final: return 1.0 # reach_prob: list of length (limit + 1) where reach_prob[score] is the probability # that the running total ever lands on 'score' (e.g. [1.0, 1/3, 4/9, ...] for W=3). reach_prob = [0.0] * (limit + 1) reach_prob[0] = 1.0 # window_sum: sum of reach_prob[prev] over active scores prev in # [score - max_points, score - 1] with prev < threshold. For score = 1, prev = 0. window_sum = 1.0 within_limit_prob = 0.0 # Phase 2: Sweep score from 1 to limit, updating the active window in O(1) per step. for score in range(1, limit + 1): # Any active prev in the window reaches 'score' only by rolling (score - prev), # which has probability 1 / max_points. reach_prob[score] = window_sum / max_points if score < threshold: # Player has not reached threshold yet, so they will draw again from 'score'. window_sum += reach_prob[score] else: # Player stops as soon as score >= threshold; count this final score<=limit, # and do NOT add it to window_sum because stopped players never draw again. within_limit_prob += reach_prob[score] # Slide the window's left edge before advancing to (score + 1): # leaving_score will be (max_points + 1) behind (score + 1), out of single-draw reach. # Only subtract if leaving_score >= 0 and was active (< threshold) when added. leaving_score = score - max_points if 0 <= leaving_score < threshold: window_sum -= reach_prob[leaving_score] return within_limit_prob✅ Submit now — all tests should pass.
Intuition & how it works
Picture hopping forward along numbered tiles 0, 1, 2, ... by spinning a fair max_points-slice wheel. Every tile before threshold says "spin again," whereas every tile from threshold onward is sticky so you halt the moment you land on it. Because every spin advances you by at least 1, you can never visit the same tile twice in a single run, which means the probability of ever landing on tile score is 1 / max_points times the sum of probabilities of all active ("spin again") tiles within max_points steps behind it.
Enumerating every branch of wheel spins explodes exponentially. Estimating the answer via random trials (Monte Carlo simulation — approximating a probability by running many random experiments and recording the fraction of successes) also fails because reducing sampling error below 1e-5 requires billions of trials. Even plain dynamic programming (computing each tile's probability in order from earlier tiles) costs O(limit * max_points) if you re-sum up to max_points predecessors from scratch each time; maintaining a sliding window (a running sum over a moving range that adds entering items and subtracts exiting items in O(1) time) eliminates that inner loop completely.
Let's walk through Example 2 (limit = 3, threshold = 2, max_points = 3):
- Tile
0:reach_prob[0] = 1.0. Since0 < 2, tile0is active, sowindow_sum = 1.0. - Tile
1:reach_prob[1] = 1.0 / 3 = 1/3. Since1 < 2, tile1is also active, updatingwindow_sumto1 + 1/3 = 4/3(1 - 3 < 0, so nothing slides out). - Tile
2:reach_prob[2] = (4/3) / 3 = 4/9. Since2 >= 2, the counter halts here! We add4/9towithin_limit_proband leavewindow_sum = 4/3unchanged (2 - 3 < 0). - Tile
3:reach_prob[3] = (4/3) / 3 = 4/9. Since3 >= 2, this also halts insidelimit = 3, bringingwithin_limit_probto4/9 + 4/9 = 8/9 ≈ 0.88889.
Complexity
- Time:
O(limit)— AfterO(1)boundary guards, we scanscoreonce from1tolimit, performing one division, one addition, and at most one subtraction per score. Wheneverlimit >= (threshold - 1) + max_points, the early guard returns1.0inO(1)time. - Space:
O(limit)—reach_probstoreslimit + 1floats soreach_prob[score - max_points]can be looked up inO(1)when it leaves the window.
Edge cases
threshold == 0: The counter starts at0 >= threshold, takes zero steps, and finishes at0 <= limit, returning1.0. Checking this before the loop prevents0from being treated as an active tile.max_points == 1: Every step adds1, guaranteeing a halt right onthresholdwith probability1.0.limit >= (threshold - 1) + max_points: Even jumpingmax_pointsfromthreshold - 1lands at or belowlimit, returning1.0.threshold == 1: A single step always halts the process, yieldingmin(limit, max_points) / max_points(Example 1).limit == threshold: Any overshoot pastthresholdmisseslimit(Example 3).limit > max_points: Active tiles (score - max_points >= 0) genuinely slide out ofwindow_summid-loop.- Floating-point precision: Every
reach_prob[score]stays in[0, 1], so double-precision rounding across10^4steps drifts by less than1e-12, well inside1e-5.
Common mistakes
- Adding halted tiles (
score >= threshold) intowindow_sum: Halted runs never spin again, soreach_prob[score]belongs inwithin_limit_prob, never inwindow_sum. - Evicting
score - max_pointsbefore computingreach_prob[score]: Tilescore - max_pointscan still reachscorevia a spin ofmax_points; subtract it only after settingreach_prob[score]. - Summing
reach_prob[0 .. limit]as the answer: Tiles belowthresholdare transient stops, not halting outcomes; onlythreshold <= score <= limitcount. - Skipping the
threshold == 0guard: Without an early return,window_sum = 1.0pretends the counter spins from0and under-reports wheneverlimit < max_points.
Follow-up questions
- How can you cut the auxiliary memory from O(limit) down to O(max_points)? At step
score, the oldest entry we ever subtract isreach_prob[score - max_points]. Storing only the most recentmax_pointsentries inside a circular buffer (a fixed-length array of sizemax_pointsindexed byscore % max_pointsthat overwrites expired slots) reduces auxiliary space toO(min(limit, max_points))while keepingO(limit)time. - What changes if step sizes 1..max_points follow a custom non-uniform probability distribution? Equal
1 / max_pointsweights are what let onewindow_sumserve every target; with custom probabilitiesp[d],reach_prob[score]is the weighted sum ofp[d] * reach_prob[score - d]over active predecessorsscore - d < threshold, takingO(limit * max_points)directly. For large limits, combining divide-and-conquer with the Fast Fourier Transform (an algorithm that computes all pairwise weighted sums between two arrays inO(n log n)time via polynomial multiplication) computes the left half ofreach_prob, pushes its contribution into the right half, and recurses inO(limit * log^2 limit)time. - How would you compute the expected number of draws taken before stopping? Let
expected_steps[s]be the average remaining draws starting at scores, which equals0fors >= thresholdand1 + (1 / max_points) * (expected_steps[s + 1] + ... + expected_steps[s + max_points])fors < threshold. Sweepingsbackward fromthreshold - 1down to0with a sliding window over the nextmax_pointsentries givesexpected_steps[0]inO(threshold)time andO(max_points)space.
Follow-up questions
- How can you cut the auxiliary memory from O(limit) down to O(max_points)?
- What changes if step sizes 1..max_points follow a custom non-uniform probability distribution?
- How would you compute the expected number of draws taken before stopping?
Similar questions
- Longest Repeat-Free Substring Ignoring Case
- Shortest Knight-Style Jumps on an Unbounded Grid
- Bidirectional Bubble Sort with Adaptive Bounds
- Immutable State Engine for a Folder Tree
- End-to-End Project Walkthrough and Engineering Ownership
- Core ML Optimization, Regularization, and Encoding
More UiPath interview questions
- Immutable State Engine for a Folder Tree Easy
- Decoder Transformers, Beam Search, and Low-Rank Adaptation Medium
- Engineering Dependable LLM Tool Use: Structured Outputs, Recovery, and Loop Control Medium Pro
- Shortest Knight-Style Jumps on an Unbounded Grid Medium Pro
- Longest Repeat-Free Substring Ignoring Case Medium Pro
- End-to-End Project Walkthrough and Engineering Ownership Medium Pro
- Core ML Optimization, Regularization, and Encoding Easy Pro
- Transformer Block Internals, Math, and Feed-Forward Role Medium Pro
- Storage Architecture and Query Consistency Guarantees Hard Pro
- Bidirectional Bubble Sort with Adaptive Bounds Medium Pro