Evaluate a Normalized CDF from Piecewise-Linear Density Samples
Math & Bit ManipulationAuto-graded · 17 test casesLast updated
Build a cumulative distribution from sampled density points using exact integration of a piecewise-linear curve, then answer many query points with correct boundary behavior.
A continuous random variable has a density that is known only at a handful of sample points. You are given the sample locations xs, the density value at each location density, and a list of queries. For each query q, return the probability that the variable is at most q.
Model
- Between two neighbouring sample locations, the density is the straight line joining the two sampled values (piecewise-linear interpolation).
- Outside the interval
[xs[0], xs[-1]], the density is zero. The variable therefore lives entirely on that interval. - The raw area under the interpolated curve is generally not 1, so divide every area by the total area under the whole curve. The returned values are probabilities of the normalized density.
Task
Implement a function that, for every query q, returns the normalized area under the interpolated density from xs[0] up to q:
- If
q <= xs[0], the answer is0.0. - If
q >= xs[-1], the answer is1.0. - Otherwise, the answer is the exact area (not an approximation by sampling) of the interpolated curve from
xs[0]toq, divided by the total area.
Results must be returned in the same order as queries. Because of floating-point rounding, clamp each result into [0.0, 1.0].
Input validation
Raise ValueError if any of these hold:
xsanddensityhave different lengths, or fewer than 2 entries.xsis not strictly increasing.- Any density value is negative.
- The total area is not positive.
Constraints
2 <= len(xs) <= 10^5xsstrictly increasing (valid inputs); density values are non-negative with positive total area.0 <= len(queries) <= 10^5; queries may be in any order and may repeat.- All numbers are finite floats or integers.
- Answers are compared with a small floating-point tolerance.
Examples
Example 1
Input: density_to_cdf([0, 1, 2], [0, 1, 0], [-1, 0, 0.5, 1, 1.5, 2, 3])
Output: [0, 0, 0.125, 0.5, 0.875, 1, 1]
Example 2
Input: density_to_cdf([0, 2], [1, 1], [0, 0.5, 1, 2])
Output: [0, 0.25, 0.5, 1]
Example 3
Input: density_to_cdf([-2, -1, 0, 1], [0, 0, 1, 1], [-3, -1, -0.5, 0, 0.5, 1, 2])
Output: [0, 0, 0.08333333333333333, 0.3333333333333333, 0.6666666666666666, 1, 1]
Hints
Hint 1
Within one segment the density is linear, so the area from the segment's left end to a point at distance t is density_left * t + slope * t^2 / 2.
Hint 2
Precompute the cumulative area at every sample location (a prefix sum of trapezoid areas) so each query needs only one partial segment.
Hint 3
Use binary search on xs to find the segment containing each query, and handle queries at or beyond the ends before doing any interpolation.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The cumulative distribution is the running area under the density. Because the density is piecewise linear, that area can be computed exactly, with no numerical approximation.
- Validate the input as described in the statement.
- Prefix areas. For each segment between neighbouring samples, the area is a trapezoid:
width * (left + right) / 2. Accumulate these intoprefix, whereprefix[i]is the area fromxs[0]toxs[i]. The last entry is the total area, used for normalization. - Answer each query.
- If
q <= xs[0], return0.0. Ifq >= xs[-1], return1.0. - Otherwise, binary search for the segment
iwithxs[i] <= q < xs[i+1]. Lett = q - xs[i]andslope = (density[i+1] - density[i]) / (xs[i+1] - xs[i]). The density at distancesinto the segment isdensity[i] + slope * s, so the area up totisdensity[i] * t + slope * t^2 / 2. - Add that to
prefix[i], divide by the total, and clamp to[0, 1].
- If
Why it is correct
- Within a segment the density is exactly a linear function, and the integral of a linear function is the quadratic used above. The prefix sums add up all complete segments to its left, so the result is the exact area from the left end to
q. - Dividing by the total area normalizes the density so the final value is exactly 1 at the right end.
- All densities are non-negative, so every increment is non-negative and the result is non-decreasing in
q. Clamping only removes floating-point overshoot. - Outside the sampled range the density is zero, which justifies returning 0 and 1 directly.
Complexity
- Building the prefix areas: O(n) time, O(n) space.
- Each query: O(log n) for the binary search, so O((n + m) log n) total for m queries (O(n + m log n) precisely).
Reference solution
from bisect import bisect_right
from typing import List
def density_to_cdf(xs: List[float], density: List[float], queries: List[float]) -> List[float]:
"""Return the normalized CDF value for each query.
The density is the piecewise-linear interpolation of (xs, density),
and is zero outside [xs[0], xs[-1]]. Raise ValueError for invalid input.
"""
n = len(xs)
if n != len(density) or n < 2:
raise ValueError("xs and density must have equal length >= 2")
if any(xs[i] >= xs[i + 1] for i in range(n - 1)):
raise ValueError("xs must be strictly increasing")
if any(y < 0 for y in density):
raise ValueError("density values must be nonnegative")
prefix = [0.0]
for i in range(n - 1):
width = xs[i + 1] - xs[i]
prefix.append(prefix[-1] + width * (density[i] + density[i + 1]) / 2.0)
total = prefix[-1]
if total <= 0:
raise ValueError("total area must be positive")
out = []
for q in queries:
if q <= xs[0]:
out.append(0.0)
elif q >= xs[-1]:
out.append(1.0)
else:
i = bisect_right(xs, q) - 1
t = q - xs[i]
slope = (density[i + 1] - density[i]) / (xs[i + 1] - xs[i])
partial = density[i] * t + slope * t * t / 2.0
value = (prefix[i] + partial) / total
out.append(min(1.0, max(0.0, value)))
return out