KatInterview

Expected Steps to Deplete Whole Pills from a Random Draw Process

Dynamic ProgrammingAuto-graded · 14 test cases
HardAuto-gradedDynamic Programmingprobabilityexpectationmarkov-chain

Last updated

Tests modeling a stochastic process as a Markov chain and solving it with dynamic programming using conditional expectation.

You begin with a container holding n complete pills. Each step, you randomly select one pill from the container with uniform probability:

  • If you select a complete pill, you consume half of it and return the remaining half to the container.
  • If you select a half pill, you consume it entirely and nothing is returned.

Your task is to compute the expected number of steps required until no complete pills remain in the container.

Constraints

  • 1 <= n <= 1000
  • Return the result as a floating-point number.
  • The process terminates when the count of complete pills reaches zero (half pills may still remain).

Examples

Example 1

Input: steps_until_no_complete(1)

Output: 1

Example 2

Input: steps_until_no_complete(2)

Output: 2.5

Hints

Hint 1

Model the system state as a pair (complete_count, half_count) and write a recurrence for the expected steps from each state.

Hint 2

The base case is when complete_count = 0, which requires zero additional steps.

Hint 3

Use dynamic programming with states ordered by increasing complete_count, then increasing half_count within each row.