KatInterview

Estimate Percentile from Histogram Buckets

Greedy & IntervalsAuto-graded · 17 test cases
MediumAuto-gradedGreedy & Intervalsmathintervalshistogram

Last 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

  1. Values within any bucket are assumed to be uniformly distributed across its $[lower, upper)$ span.
  2. If p targets 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})$$ where target = p * total_count, and cumulative is the sum of counts in all strictly preceding buckets.
  3. Buckets with count <= 0 carry no mass and should be ignored during interpolation.
  4. If the target rank lands in a bucket where the upper bound is infinite (math.inf), or if the calculated position falls beyond finite bounds, raise a ValueError.
  5. If p <= 0 or p > 1, or if the total observation count is zero or negative, raise a ValueError.

Constraints

  • $1 \le \text{len(buckets)} \le 10^4$
  • buckets are sorted by lower bound 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.