Skip to content
BytePatterns

Latency Percentiles by Nearest Rank

EasySystem Design#percentiles#sorting~10m

Problem

A dashboard reports request latency as percentiles rather than an average. Given a list of latency samples in milliseconds and a list of percentiles such as [50, 90, 99], return a dict from each percentile to its value using the nearest-rank method: sort the samples, and the p-th percentile is the sample at 1-based rank ceil(p × n / 100), where n is the number of samples. Use integer arithmetic for the rank. There are up to 1,000,000 samples.

Examples

Input:  latencies = [12, 15, 11, 13, 240, 14, 12, 16, 13, 12], ps = [50, 90, 99]
Output: {50: 13, 90: 16, 99: 240}
Why:    one slow request out of ten is invisible at p90 and is the whole story at p99
Input:  latencies = 1 to 100, ps = [50, 90, 99, 100]
Output: {50: 50, 90: 90, 99: 99, 100: 100}
Why:    with 100 samples the p-th percentile is simply the p-th smallest
Input:  latencies = [7], ps = [50, 99]
Output: {50: 7, 99: 7}
Why:    edge case, a single sample is every percentile

Hints

0 / 3

Stuck on the idea rather than the code? Observability Basics covers it.