KatInterview

Probability of Adjacent Car Groups in a Random Parking Row

Dynamic ProgrammingAuto-graded · 24 test cases
MediumAuto-gradedDynamic Programmingcombinatoricsprobabilitydynamic-programming

Last updated

Count placements of k items in n slots with at least m maximal runs of length 2 or more, using a counting DP or combinatorics, and return the exact probability.

Random Parking Row

A parking row has n spaces in a line. Exactly k cars are parked in it, at most one per space. Every way of choosing which k of the n spaces are occupied is equally likely. Only the set of occupied spaces matters, and the cars are not labeled.

A group is a maximal block of consecutive occupied spaces that contains at least 2 spaces. "Maximal" means the block cannot be extended on either side. For example, with n = 5:

  • 11100 has exactly one group, of length 3. It does not count as two overlapping pairs.
  • 10101 has no groups.
  • 11011 has two groups.

Write a function that takes n, k and m, and returns the probability that a random arrangement contains at least m groups.

This is the exact upper-tail probability of the group count under uniform random placement. A p-value for observing m groups would be defined the same way.

Details

  • The result is the number of arrangements with at least m groups, divided by the total number of arrangements, C(n, k).
  • If m <= 0, every arrangement qualifies and the answer is 1.0.
  • If m is larger than any arrangement can reach, the answer is 0.
  • Return a float. A value of 0 is acceptable when the probability is zero.

Constraints

  • 1 <= k < n
  • n and k are small enough that an exact count is feasible (for example n up to a few dozen).
  • m is an integer, normally m >= 1.

Examples

Example 1

Input: adjacent_group_probability(3, 2, 1)

Output: 0.6666666666666666

Example 2

Input: adjacent_group_probability(5, 2, 1)

Output: 0.4

Example 3

Input: adjacent_group_probability(5, 3, 1)

Output: 0.9

Example 4

Input: adjacent_group_probability(5, 3, 2)

Output: 0

Hints

Hint 1

Each arrangement is a binary string of length n with exactly k ones. The answer is a ratio of counts, so count the favorable strings exactly instead of simulating.

Hint 2

Scan the row left to right. Track how many cars have been placed, how many groups have been formed so far, and whether the current run of occupied spaces has length 0, 1, or 2 or more.

Hint 3

A new group is created exactly when a car is placed right after a run of length 1, which makes the run length 2. Placing more cars into a run that is already 2 or longer adds no new group. Divide the final count by C(n, k).