Coding
Quant Python

Hitting a Total

Difficulty

Asked at Da Vinci Derivatives

Theory: Quant Python That Survives Review

Read the problem, hints and solution here. The editor needs a bigger screen: open this page on a laptop to write and run your code.

You roll a fair six-sided die repeatedly and keep a running total. What is the probability that the running total is ever exactly \(n\)?

Implement probability_hits_total(n) returning that probability rounded to 6 decimal places (use Python's round(p, 6)).

Examples

probability_hits_total(1)
# 0.166667  (you must roll a 1 first)

probability_hits_total(2)
# 0.194444  (roll a 2, or roll 1 then 1: 1/6 + 1/36 = 7/36)

probability_hits_total(7)
# 0.253604

Constraints

  • 1 <= n <= 200000.
  • Your solution should be linear in \(n\): enumerating roll sequences explodes combinatorially and will not finish for even moderate \(n\).

This is a classic trading-interview probability question; the coding version asks you to turn the recurrence you would state at the whiteboard into a correct, fast implementation, and to notice what happens for large \(n\).

Rate this problem
Language: Pythonprobability_hits_total
Sample tests

Run your code to check it against the sample tests. Results appear here.

Rate this problem
Next in Quant Dev 50LRU Cache, Then Extend It