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^4
  • 1 <= max_points <= 10^4

Step-by-step walkthrough

  1. Understand the process and the possible halting scores

    The counter starts at 0. Whenever the current score is strictly below threshold, we roll a fair max_points-sided die (adding a uniform integer from 1 to max_points). The instant the score reaches threshold or higher, the process halts immediately. We want the probability that this halting score is at most limit.

    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 W denotes max_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 at threshold - 1 or below and adds at most max_points.
  2. 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 on score during a run:

    • Every run begins at 0, so reach_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. Reaching score from predecessor prev = 1 and reaching score from prev = 2 are mutually exclusive events (two events that can never occur in the same run), so their probabilities simply add!
    • Which predecessors prev can jump straight to score in a single step?
      1. prev must lie within one step's reach: score - max_points <= prev <= score - 1 (with prev >= 0).
      2. The counter must still have been active at prev, meaning prev < threshold.
      3. From prev, we must roll the exact gap score - prev, which happens with probability 1 / 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 < threshold
    

    For any score >= threshold, touching score halts the run immediately, so reach_prob[score] equals the exact probability of finishing at score. Summing reach_prob[score] across threshold <= score <= limit yields our answer.

  3. Why naive summation and random trials fall short

    Summing up to max_points predecessors from scratch for every score takes O(limit * max_points) operations. At limit = 10^4 and max_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 guarantee 1e-5 accuracy.

  4. Key idea: maintain a sliding window of active scores

    Compare the active predecessors summed for consecutive scores when max_points = 3 and threshold = 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 score to score + 1 changes the predecessor sum in at most two places! A single variable window_sum updates in O(1) time per score:

    1. Set reach_prob[score] = window_sum / max_points.
    2. If score < threshold, the process remains active at score, so add reach_prob[score] to window_sum. Otherwise (score >= threshold), the process halts at score, so add reach_prob[score] to within_limit_prob instead (never to window_sum).
    3. Before advancing to score + 1, inspect leaving_score = score - max_points. Whenever 0 <= leaving_score < threshold, subtract reach_prob[leaving_score] from window_sum because leaving_score can no longer reach score + 1 in one step.
  5. Handle the boundary cases up front

    Three O(1) guards dispose of corner cases before the loop:

    • limit < threshold: halting below threshold is impossible, so return 0.0.
    • threshold == 0: the counter starts at 0 >= threshold, takes zero steps, and halts at 0 <= limit, so return 1.0. Returning early is critical: otherwise window_sum = 1.0 would treat 0 as an active score!
    • limit >= (threshold - 1) + max_points: even the largest possible halting score is <= limit, so return 1.0 immediately.
        # 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.0
    
  6. Code the sliding-window loop

    We allocate reach_prob only through index limit, since scores past limit neither contribute to within_limit_prob nor feed smaller scores. Note that the eviction guard checks 0 <= leaving_score < threshold so we only subtract valid scores that were actually added into window_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_prob
    
  7. Trace Example 3 step by step

    Trace limit = 4, threshold = 4, max_points = 2. Here max_possible_final = (4 - 1) + 2 = 5, and 4 < 5, so we sweep score = 1..4 (watch how leaving_score evicts 0 and 1 along 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/8
    

    The loop returns within_limit_prob = 11/16 = 0.6875, matching Example 3. Notice that the leftover window_sum = 5/8 corresponds to reach_prob[5] = (5/8) / 2 = 5/16, and 11/16 + 5/16 = 1!

  8. 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):

  1. Tile 0: reach_prob[0] = 1.0. Since 0 < 2, tile 0 is active, so window_sum = 1.0.
  2. Tile 1: reach_prob[1] = 1.0 / 3 = 1/3. Since 1 < 2, tile 1 is also active, updating window_sum to 1 + 1/3 = 4/3 (1 - 3 < 0, so nothing slides out).
  3. Tile 2: reach_prob[2] = (4/3) / 3 = 4/9. Since 2 >= 2, the counter halts here! We add 4/9 to within_limit_prob and leave window_sum = 4/3 unchanged (2 - 3 < 0).
  4. Tile 3: reach_prob[3] = (4/3) / 3 = 4/9. Since 3 >= 2, this also halts inside limit = 3, bringing within_limit_prob to 4/9 + 4/9 = 8/9 ≈ 0.88889.

Complexity

  • Time: O(limit) — After O(1) boundary guards, we scan score once from 1 to limit, performing one division, one addition, and at most one subtraction per score. Whenever limit >= (threshold - 1) + max_points, the early guard returns 1.0 in O(1) time.
  • Space: O(limit) — reach_prob stores limit + 1 floats so reach_prob[score - max_points] can be looked up in O(1) when it leaves the window.

Edge cases

  • threshold == 0: The counter starts at 0 >= threshold, takes zero steps, and finishes at 0 <= limit, returning 1.0. Checking this before the loop prevents 0 from being treated as an active tile.
  • max_points == 1: Every step adds 1, guaranteeing a halt right on threshold with probability 1.0.
  • limit >= (threshold - 1) + max_points: Even jumping max_points from threshold - 1 lands at or below limit, returning 1.0.
  • threshold == 1: A single step always halts the process, yielding min(limit, max_points) / max_points (Example 1).
  • limit == threshold: Any overshoot past threshold misses limit (Example 3).
  • limit > max_points: Active tiles (score - max_points >= 0) genuinely slide out of window_sum mid-loop.
  • Floating-point precision: Every reach_prob[score] stays in [0, 1], so double-precision rounding across 10^4 steps drifts by less than 1e-12, well inside 1e-5.

Common mistakes

  • Adding halted tiles (score >= threshold) into window_sum: Halted runs never spin again, so reach_prob[score] belongs in within_limit_prob, never in window_sum.
  • Evicting score - max_points before computing reach_prob[score]: Tile score - max_points can still reach score via a spin of max_points; subtract it only after setting reach_prob[score].
  • Summing reach_prob[0 .. limit] as the answer: Tiles below threshold are transient stops, not halting outcomes; only threshold <= score <= limit count.
  • Skipping the threshold == 0 guard: Without an early return, window_sum = 1.0 pretends the counter spins from 0 and under-reports whenever limit < 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 is reach_prob[score - max_points]. Storing only the most recent max_points entries inside a circular buffer (a fixed-length array of size max_points indexed by score % max_points that overwrites expired slots) reduces auxiliary space to O(min(limit, max_points)) while keeping O(limit) time.
  • What changes if step sizes 1..max_points follow a custom non-uniform probability distribution? Equal 1 / max_points weights are what let one window_sum serve every target; with custom probabilities p[d], reach_prob[score] is the weighted sum of p[d] * reach_prob[score - d] over active predecessors score - d < threshold, taking O(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 in O(n log n) time via polynomial multiplication) computes the left half of reach_prob, pushes its contribution into the right half, and recurses in O(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 score s, which equals 0 for s >= threshold and 1 + (1 / max_points) * (expected_steps[s + 1] + ... + expected_steps[s + max_points]) for s < threshold. Sweeping s backward from threshold - 1 down to 0 with a sliding window over the next max_points entries gives expected_steps[0] in O(threshold) time and O(max_points) space.

Follow-up questions

Similar questions

More UiPath interview questions

All 13 UiPath questions →