Estimate Percentile from Histogram Buckets
Greedy & IntervalsAuto-graded · 17 test casesLast updated
Linearly interpolate a percentile value across histogram buckets assuming uniform distribution within each interval.
Given a list of histogram bucket intervals representing data distribution and a target percentile rank $p$ (where $0 < p \le 1$), estimate the value corresponding to that percentile.
Each bucket is represented as a dictionary with three fields:
lower: The inclusive lower numerical bound of the bucket interval.upper: The exclusive upper numerical bound of the bucket interval.count: The number of observations falling into this interval.
Assumptions & Behavior
- Values within any bucket are assumed to be uniformly distributed across its $[lower, upper)$ span.
- If
ptargets a position within a bucket, linear interpolation is used: $$\text{value} = \text{lower} + \frac{\text{target} - \text{cumulative}}{\text{count}} \times (\text{upper} - \text{lower})$$ wheretarget = p * total_count, andcumulativeis the sum of counts in all strictly preceding buckets. - Buckets with
count <= 0carry no mass and should be ignored during interpolation. - If the target rank lands in a bucket where the
upperbound is infinite (math.inf), or if the calculated position falls beyond finite bounds, raise aValueError. - If
p <= 0orp > 1, or if the total observation count is zero or negative, raise aValueError.
Constraints
- $1 \le \text{len(buckets)} \le 10^4$
bucketsare sorted bylowerbound in non-decreasing order.- $0 \le \text{count} \le 10^9$ for each bucket.
- $0 < p \le 1$.
Examples
Example 1
Input: estimate_percentile([{'lower': 0, 'upper': 10, 'count': 50}, {'lower': 10, 'upper': 50, 'count': 50}], 0.75)
Output: 30
Hints
Hint 1
Calculate the total number of observations across all buckets to find the target rank `target = p * total_count`.
Hint 2
Iterate through the buckets while tracking the cumulative sum of counts from previous non-empty buckets.
Hint 3
When you encounter the first non-empty bucket where `cumulative + count >= target`, perform linear interpolation within that bucket interval.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To estimate a percentile from histogram data under the assumption of uniformity within intervals:
- Input Validation: Ensure $0 < p \le 1$ and that the total count of observations across all buckets is positive.
- Target Rank Calculation: Compute $\text{target} = p \times \text{total_count}$.
- Bucket Identification: Traverse the sorted bucket list sequentially while updating a running
cumulativecount of observations seen so far. Skip buckets withcount <= 0. - Linear Interpolation: The first bucket where $\text{cumulative} + \text{count} \ge \text{target}$ contains the desired percentile:
- Determine how far into this bucket the target falls: $\text{fraction} = \frac{\text{target} - \text{cumulative}}{\text{count}}$.
- Check if the upper bound is finite; if
math.isfinite(upper)is false, raise aValueError. - Calculate the estimated value as $\text{lower} + \text{fraction} \times (\text{upper} - \text{lower})$.
Complexity
- Time Complexity: $\mathcal{O}(N)$ where $N$ is the number of buckets, as we iterate through the list at most twice.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space.
Python Reference Solution
import math
from typing import Dict, List
def estimate_percentile(buckets: List[Dict], p: float) -> float:
if not (0 < p <= 1):
raise ValueError("p must be in (0, 1]")
total = sum(bucket["count"] for bucket in buckets)
if total <= 0:
raise ValueError("buckets must contain observations")
target = p * total
cumulative = 0
for bucket in buckets:
count = bucket["count"]
if count <= 0:
continue
next_cumulative = cumulative + count
if target <= next_cumulative:
lower = bucket["lower"]
upper = bucket["upper"]
if not math.isfinite(upper):
raise ValueError("cannot estimate a finite percentile in an open-ended bucket")
fraction = (target - cumulative) / count
return lower + fraction * (upper - lower)
cumulative = next_cumulative
bucket = next(b for b in reversed(buckets) if b["count"] > 0)
if not math.isfinite(bucket["upper"]):
raise ValueError("cannot estimate a finite percentile in an open-ended bucket")
return bucket["upper"]