KatInterview

Waiting-Time Triangle Density: Normalize and Evaluate the CDF

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingprobabilitycdfpiecewise-functions

Last updated

Normalize a piecewise-linear triangular density to find its constant, then evaluate the resulting piecewise-quadratic cumulative distribution at a list of query points.

A continuous random variable X models how long (in hours) a customer waits for a pickup. Its density has a triangular shape, controlled by one positive constant c:

  • f(x) = c * x when 0 <= x < 2
  • f(x) = c * (4 - x) when 2 <= x <= 4
  • f(x) = 0 for every other x

Write a function that does two things:

  1. Finds the constant c that makes f a valid probability density, meaning the total area under it equals 1.
  2. Evaluates the cumulative distribution function F(t) = P(X <= t) at each query point in a given list.

Because the density is defined piecewise, F is also piecewise. It is 0 to the left of the support, 1 to the right of it, and it must stay continuous (in particular at t = 2, where the accumulated probability from the rising part must be carried into the falling part).

Input

  • queries: a list of real numbers, the points at which to evaluate F.

Output

Return a dictionary with two keys:

  • "k": the normalizing constant c, as a float.
  • "values": a list of floats, where the i-th entry is F(queries[i]), in the same order as the input.

Constraints

  • 0 <= len(queries) <= 10^5
  • Each query is a finite real number (it may be negative, zero, or larger than 4).
  • Queries may repeat and need not be sorted.
  • Results are compared to the expected values with a small floating-point tolerance.

Examples

Example 1

Input: triangle_wait_cdf([-1, 0, 0.5, 1, 2, 3, 4, 5])

Output: {'k': 0.25, 'values': [0, 0, 0.03125, 0.125, 0.5, 0.875, 1, 1]}

Example 2

Input: triangle_wait_cdf([-10, 0, 2, 4, 10])

Output: {'k': 0.25, 'values': [0, 0, 0.5, 1, 1]}

Example 3

Input: triangle_wait_cdf([0, 1, 1.5, 2, 2.5, 3.5, 4])

Output: {'k': 0.25, 'values': [0, 0.125, 0.28125, 0.5, 0.71875, 0.96875, 1]}

Hints

Hint 1

The density is a triangle with base 4 and peak height 2c at x = 2. Set its area equal to 1 to get c.

Hint 2

For 0 <= t < 2, integrate c*s from 0 to t. For t >= 2, start from the mass already accumulated at t = 2 and add the integral of the falling part.

Hint 3

Handle the tails explicitly: F(t) = 0 for t < 0 and F(t) = 1 for t > 4. Check that both middle pieces give 1/2 at t = 2.