Skip to content
Coding · Hard · Aggregation · Target O(b log b) · Staff

Percentile from histogram buckets

Estimate a quantile from cumulative histogram buckets by interpolating inside the right bucket, and get the empty, first-bucket and +Inf cases right.

Statement

A latency histogram is exported as cumulative buckets: (upper_bound, cumulative_count) pairs, where cumulative_count is the number of observations less than or equal to upper_bound. The largest bound is float("inf") and its count is the total. Write quantile(q, buckets) that estimates the q-quantile, for q from 0 to 1, on the assumption that observations are spread evenly inside each bucket.

Sort the buckets by upper bound. The rank is q × total. A bucket's own count is its cumulative count minus the cumulative count of the bucket before it. The answer lies in the first bucket that has at least one observation of its own and whose cumulative count is at least the rank. Inside it, return lower + (upper − lower) × (rank − cumulative count before this bucket) ÷ (this bucket's own count), where lower is the upper bound of the bucket before it.

Edges. The first bucket has no bucket before it: use 0 as its lower edge when its upper bound is positive, otherwise return its upper bound. If the answer lies in the +Inf bucket, return the highest finite upper bound, because nothing more is known. Return None for an empty list, for a total of 0, and for a histogram whose only bucket is +Inf.

Raise ValueError when q is not between 0 and 1 (NaN included), when the largest bound is not +Inf, or when a cumulative count is lower than the one before it.

Examples

buckets = [(0.1, 10), (0.5, 60), (1.0, 90), (inf, 100)]

q = 0.5   → 0.42   # rank 50 is in (0.1, 0.5]: 0.1 + 0.4 × (50 − 10) ÷ 50
q = 0.75  → 0.75   # rank 75 is in (0.5, 1.0]: 0.5 + 0.5 × (75 − 60) ÷ 30
q = 0.05  → 0.05   # rank 5 is in the first bucket: 0 + 0.1 × 5 ÷ 10
q = 0.95  → 1.0    # rank 95 is in the +Inf bucket
q = 0     → 0.0    # the lower edge of the first non-empty bucket

Constraints

Up to 10⁵ buckets, in any order, with distinct bounds. Bounds may be negative. Counts are non-negative integers. Results are compared with a tolerance of 10⁻⁹.

Open to everyone until Pro goes on sale · sign in to save your attemptSolve it in the editor with visible tests
Open in the app