Probability of landing in a range on a dice walk
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's first round (coding), last asked Mar 2026. It tests probability and dynamic programming.
You start at position 0 on an endless number line. Each turn you roll a fair die with faces 1 to k and move forward that many steps. The game stops as soon as your position is at least mn. You win if you stop inside [mn, mx] and lose if you jump past mx. Return the probability of winning, computed exactly, not by simulation.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
win_probability(k: int, mn: int, mx: int) -> float— answers within10^-6are accepted.
Example
win_probability(2, 3, 3) -> 0.625
# win only by stopping exactly on 3: rolls 1-1-1, 1-2 or 2-1, so 1/8 + 1/4 + 1/4 = 5/8
win_probability(3, 1, 2) -> 0.666667 # one roll; win on 1 or 2
win_probability(6, 4, 6) -> 0.793981 # exactly 343/432
win_probability(10, 0, 5) -> 1.0 # position 0 is already in range
Constraints
-
0 <= mn <= mx <= 10^5;1 <= k <= 10^5.
Clarifying questions
- Does the game stop as soon as the position reaches
mn, or can you keep rolling inside the range? - If
mnis 0, have you already won? - Is an exact fraction wanted, or a float within a tolerance?
What a strong answer covers
- Let
p[s]be the probability of ever standing onswhile still playing.p[0] = 1, and fors >= 1,p[s] = (1/k) * sum(p[t])overtin[s - k, s - 1]witht < mn(you only roll again from positions belowmn). - The answer is the sum of
p[s]forsin[mn, mx]. - A sliding-window sum makes each state
O(1):O(mx)time instead ofO(mx * k), andO(mx)orO(k)memory. - A shortcut: if
mx - mn + 1 >= kandmn >= 1, the jump from belowmncan never passmx, so the answer is 1. - Precision of floats over long sums; exact fractions for small inputs to test against.
Follow-ups
- Return the expected number of rolls.
- The die is not fair: face
ihas probabilityq[i]. - Win if you ever land in the range, but keep rolling after it (the game stops only beyond
mx). What changes?
Where it's asked
- Google · First round: coding · Last asked Mar 202645 min · Coding in a Google Doc, no syntax highlighting or autocomplete · No AI
What it tests
probability · dynamic programming
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
