KatInterview

Shelf Stock Versus Random Demand in a Checkout Line

Math & Bit ManipulationAuto-graded · 21 test cases
EasyAuto-gradedMath & Bit Manipulationprobabilitybinomialcombinatorics

Last updated

Compute binomial probabilities that a limited stock covers random demand from a line of customers, both as at most M buyers and as exactly M buyers.

A line of customers shoppers is waiting at a checkout. Every shopper independently picks exactly one of two products. With probability p_scarce they pick the scarce product, and otherwise (probability 1 - p_scarce) they pick the other one, which is always in plentiful supply. Each shopper takes exactly one unit.

The shop has only units copies of the scarce product left. Let X be the number of shoppers who choose the scarce product.

Write a function that returns two probabilities as a dictionary:

  • "enough": the probability that the stock covers everyone who wants the scarce product, that is, P(X <= units).
  • "exactly_enough": the probability that the stock is used up exactly, that is, P(X = units).

Details

  • X follows a binomial distribution with customers trials and success probability p_scarce.
  • If units >= customers, then "enough" is 1.0, because demand can never exceed the line length.
  • If units > customers, then "exactly_enough" is 0.0, because demand can never reach units.
  • Return a dictionary with exactly the keys "enough" and "exactly_enough", each mapped to a float.
  • Floating-point results are expected. Compute directly from the binomial formula, using 1.0 - p_scarce for the complementary probability.

Constraints

  • customers is a positive integer.
  • units is a nonnegative integer.
  • 0 < p_scarce < 1.
  • Each shopper's choice is independent of the others and of the remaining stock.

Examples

Example 1

Input: shelf_stock_probabilities(5, 2, 0.4)

Output: {'enough': 0.68256, 'exactly_enough': 0.3456}

Example 2

Input: shelf_stock_probabilities(3, 0, 0.7)

Output: {'enough': 0.027000000000000014, 'exactly_enough': 0.027000000000000014}

Example 3

Input: shelf_stock_probabilities(4, 4, 0.25)

Output: {'enough': 1, 'exactly_enough': 0.00390625}

Hints

Hint 1

The number of shoppers who want the scarce product is a sum of independent yes/no choices. Which standard distribution is that?

Hint 2

The probability of exactly k buyers is C(n, k) * p^k * (1-p)^(n-k). The 'enough' event is the sum of this over k from 0 to units.

Hint 3

Handle units >= customers separately: 'enough' is then 1.0, and 'exactly_enough' is 0.0 when units is strictly greater than customers.