KatInterview

Score Bust Probability: Stop When You Hit the Target

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingsliding-windowprobability

Last updated

Tests whether a candidate can build an O(n) sliding-window DP to compute the probability that a random accumulation process stops within a given score ceiling.

Problem

You are simulating a simple scoring game. A player starts at 0 points and keeps rolling a fair die that produces an integer uniformly at random between 1 and sides (inclusive). After each roll the result is added to the player's running total. The player stops the moment their total reaches or exceeds goal.

Return the probability that the player's final total is at most ceiling.

Rules

  • If goal is 0, the player never rolls. Their final total is 0, so the probability is 1.0.
  • An answer is accepted if it differs from the exact probability by no more than 1e-5 in absolute terms.

Constraints

  • 0 <= goal <= ceiling <= 10^4
  • 1 <= sides <= 10^4

Examples

Example 1

Input: score_within_ceiling(6, 1, 10)

Output: 0.6

Example 2

Input: score_within_ceiling(2, 2, 2)

Output: 0.75

Example 3

Input: score_within_ceiling(4, 3, 3)

Output: 0.8518518518518519

Hints

Hint 1

Define dp[x] as the probability that the running total lands on exactly x at some point during the game. Only totals below goal can trigger another roll — totals at or above goal are terminal.

Hint 2

The recurrence dp[x] = (1/sides) * sum(dp[y] for y in [x-sides, x-1] if y < goal) looks like an O(n * sides) computation, but the inner sum changes by at most two terms as x increases by one — that's a sliding window.

Hint 3

Be careful about which states feed the window. A terminal state (total >= goal) must never be added back into the window; including it would inflate every subsequent probability. Handle goal == 0 up front to avoid an off-by-one on the first iteration.