KatInterview

Probability Inventory Covers Random Demand

Arrays & HashingAuto-graded · 18 test cases
EasyAuto-gradedArrays & Hashingprobabilitybinomial-distributioncombinatorics

Last updated

Compute the binomial CDF: the chance that at most s of n independent customers request a limited item.

Implement a function demand_covered(stock: int, shoppers: int, request_probability: float) -> float that returns the probability that a stock of stock units is enough for shoppers independent customers.

Each customer, independently of the others, requests the limited item with probability request_probability, and otherwise requests something else that is always available. The stock suffices exactly when the total number of customers requesting the item is less than or equal to stock.

Return the exact probability as a Python float.

Rules and edge cases:

  • The number of item requests follows a binomial distribution with shoppers trials and success probability request_probability.
  • If stock >= shoppers, return 1.0 (demand can never exceed the number of shoppers).
  • If stock < 0 or shoppers < 0, return 0.0.
  • Customers are interchangeable; arrival order is irrelevant.

Constraints:

  • 0 <= shoppers <= 1000
  • -1 <= stock <= 1000
  • 0.0 <= request_probability <= 1.0
  • Return value lies in [0.0, 1.0]
  • Answers are checked with a tolerance of 1e-9

Examples

Example 1

Input: demand_covered(2, 5, 0.3)

Output: 0.8369199999999998

Hints

Hint 1

Let X count how many of the shoppers request the item; X follows Binomial(shoppers, request_probability).

Hint 2

The stock suffices when X <= stock, so sum P(X = k) for k from 0 to stock.

Hint 3

Each term is comb(shoppers, k) * p**k * (1-p)**(shoppers-k); handle the shortcuts when stock >= shoppers or when inputs are negative.