KatInterview

Uniform Random Sampling and Histogram Percentile Calculation

Statistics & ExperimentsModel answer
MediumModel answerStatistics & Experimentsprobabilitysamplinginterpolation

Last updated

Generate uniformly distributed points in a square region and compute percentiles from binned frequency data using linear interpolation.

You need to solve two independent probability and statistics problems.

Problem 1: Random Point Generation

You have access to a function rand01() that produces a uniformly random floating-point number in [0, 1). Your task is to generate a uniformly random point (x, y) inside a square region with corners at (0, 0) and (S, S).

Write a function that returns such a point.

Problem 2: Percentile from Histogram

You are analyzing a dataset that has been aggregated into a histogram with M bins. You receive:

  • bin_edges: An array of M+1 boundary values [e_0, e_1, ..., e_M] where bin i covers the interval [e_i, e_{i+1})
  • bin_counts: An array of M integers [c_0, c_1, ..., c_{M-1}] where c_i is how many data points fell into bin i
  • p: A percentile value between 0 and 1 (for example, 0.75 represents the 75th percentile)

Implement a function that estimates the p-th percentile value by assuming uniform distribution of points within each bin and using linear interpolation.

Example Walkthrough

Given:

  • bin_edges = [0, 10, 20, 30]
  • bin_counts = [100, 200, 100]
  • p = 0.50

Solution steps:

  1. Total observations = 100 + 200 + 100 = 400
  2. Target position = 0.50 × 400 = 200
  3. Cumulative counts: 100 (after bin 0), 300 (after bin 1)
  4. Position 200 lies in bin 1, which spans [10, 20)
  5. Within bin 1: we need the 100th out of 200 values (since 100 came before)
  6. Interpolated value = 10 + (100/200) × (20 - 10) = 15

Assumptions and Constraints

  • All bin counts are non-negative integers
  • Bin edges are in strictly increasing order
  • Percentile p is in the range [0, 1]
  • Assume data is uniformly distributed within each bin

Hints

Hint 1

For the square sampling: each coordinate can be generated independently by scaling the [0,1) random value to [0,S)

Hint 2

For percentiles: first find which bin contains your target rank by accumulating counts from left to right

Hint 3

Use the formula: value = left_edge + (fraction_through_bin) × bin_width, where fraction depends on how many values you need from that bin