PIXELBANKv9.1.0
Menu

Aggregate Latency Histogram Buckets to a Quantile

Problem Statement

Prometheus-style latency histograms store cumulative counts per bucket boundary. Estimate a quantile by linear interpolation within the bucket where the quantile rank falls.

Background

Buckets are given as ascending (upper_bound, cumulative_count) pairs (cumulative = number of samples <= upper_bound). The last bucket's count is the total. For quantile q, the target rank is q * total. Find the first bucket whose cumulative count >= rank; linearly interpolate between the previous bucket's upper bound (or 0) and this bucket's upper bound based on where rank falls within [prev_count, this_count].

Your Task

def histogram_quantile(buckets, q):

Return the estimated quantile value (float), rounded to 4 decimals.

Input Format

  • buckets (list of (upper_bound, cumulative_count), ascending), q (float in [0,1]).

Output Format

  • A float rounded to 4 decimals.

Sample

print(histogram_quantile([(1.0, 10), (2.0, 20), (5.0, 30)], 0.5))

Output:

1.5

Example:

Input:
print(histogram_quantile([(1.0, 10), (2.0, 20), (5.0, 30)], 0.5))
Output:
1.5
Reasoning:
  • Determine the total number of samples from the last bucket's cumulative count: total=30total = 30.
  • Calculate the target rank for the 50th percentile (q=0.5q = 0.5): rank=0.5×30=15rank = 0.5 \times 30 = 15.
  • Identify the bucket containing the rank by finding the first cumulative count ≥15\ge 15: the first bucket has count 1010 (too low), and the second has count 2020 (sufficient), so the relevant interval is between bounds 1.01.0 and 2.02.0.
  • Compute the linear interpolation fraction within this bucket, using the previous cumulative count (1010) and the current span (20−10=1020 - 10 = 10): frac=15−1010=0.5frac = \frac{15 - 10}{10} = 0.5.
  • Apply the fraction to the bucket width to estimate the value: 1.0+0.5×(2.0−1.0)=1.51.0 + 0.5 \times (2.0 - 1.0) = 1.5.
  • The final output is 1.5

Constraints:

  • rank = q * total (total = last cumulative count).
  • Interpolate in the bucket where cumulative first reaches rank, between prev bound (or 0) and this bound over [prev_count, this_count].
  • Round to 4 decimals; buckets non-empty and ascending.
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.