← All Exercises

Histogram Quantile with Linear Interpolation

advancedjavascript~25min

Background

Monitoring systems store latency distributions as bucketed histograms and reconstruct quantiles by interpolation. Knowing the interpolation rule explains why p99 readings jump when a bucket boundary sits mid-range.

Problem

Given cumulative-bucket boundaries and per-bucket counts, answer a quantile query. The target rank is quantile times the total count. Walk buckets accumulating counts; in the first bucket whose cumulative count reaches the target rank, interpolate linearly between the bucket lower and upper boundaries using the rank offset within that bucket. Output the quantile and the interpolated value rounded to two decimals.

Input

A JSON object {"boundaries": number[], "counts": number[], "quantile": number} where counts[i] counts observations in (boundaries[i-1], boundaries[i]] and boundaries[0] closes the first bucket from zero.

Output

A JSON object {"quantile": number, "value": number} with value rounded to two decimals.

Sample tests

Sample 1

Input: {"boundaries":[10,50,100,500],"counts":[2,3,4,1],"quantile":0.95}
Expected: {"quantile":0.95,"value":300}

Sample 2

Input: {"boundaries":[10,50,100],"counts":[5,5,10],"quantile":0.5}
Expected: {"quantile":0.5,"value":50}

Your solution

Learning objective

Reconstruct quantiles from bucketed data and understand interpolation artifacts.