Circle Point Generation, Strict Monotonic Run, and Histogram Interpolation
Math & Bit ManipulationModel answerLast updated
Solve three foundational tasks: uniform random sampling within a disk, tracking the longest strictly increasing contiguous array, and computing bucketed percentiles.
This technical assessment consists of three distinct computational tasks covering probability, linear array processing, and numerical interpolation.
Task 1: Disk Point Generation
Implement a function generate_disk_point(radius) that generates a coordinate point $(x, y)$ uniformly distributed across the interior (and boundary) of a circle centered at $(0, 0)$ with a given positive radius $R$.
Task 2: Longest Monotonic Ascending Sequence
Implement a function longest_ascending_run(sequence) that finds the length of the longest contiguous sequence of elements that is strictly increasing (i.e., each element must be strictly greater than its predecessor).
Example:
- For
sequence = [1, 3, 5, 4, 7], the function returns3(corresponding to[1, 3, 5]).
Task 3: Bucket-Based Quantile Approximation
You are given a list of non-overlapping, sorted continuous histogram bins defined as tuples: (min_val, max_val, count). Assuming that values within each bin are uniformly distributed across its range, implement a function approximate_percentile(bins, percentile) that returns the estimated numerical value at the specified percentile ($0 \le p \le 100$).
Example:
- Bins:
[(0, 10, 50), (10, 20, 50)] percentile = 75- Output:
15.0 - Reasoning: The overall sample count is 100. The target rank is $100 \times \frac{75}{100} = 75$. The first bin accounts for 50 samples. The second bin holds 50 samples between 10 and 20. We require 25 additional samples in the second bin, yielding $10 + (20 - 10) \times \frac{25}{50} = 15.0$.
Constraints
- $R > 0$
- $0 \le \text{len}(sequence) \le 10^5$
binsis ordered bymin_val, covering contiguous intervals without gaps or overlaps.- $0 \le percentile \le 100$
Hints
Hint 1
For uniform sampling over a 2D surface area, recall that area scales quadratically with distance from the origin. Linear sampling of radii leads to central clustering.
Hint 2
In Task 2, strictly increasing means sequence[i] > sequence[i-1]. Equal elements reset the current run length back to 1.
Hint 3
For Task 3, remember to filter out or safely skip bins with a count of 0 to avoid division by zero errors during linear interpolation.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Task 1: Disk Point Generation
Approach
To sample uniformly from a circle of radius $R$:
- Choose an angle $\theta$ uniformly from $[0, 2\pi)$.
- The cumulative distribution function (CDF) for distance $r$ from the origin is given by the area fraction: $$F(r) = \frac{\pi r^2}{\pi R^2} = \left(\frac{r}{R}\right)^2$$ Using inverse transform sampling, set $u \sim \text{Uniform}(0, 1)$, giving $u = (r/R)^2 \implies r = R \sqrt{u}$.
- Convert polar coordinates to Cartesian coordinates: $x = r \cos(\theta)$, $y = r \sin(\theta)$.
An alternative method is rejection sampling: sample $(x, y)$ uniformly inside the bounding box $[-R, R] \times [-R, R]$ until $x^2 + y^2 \le R^2$. The acceptance rate is $\frac{\pi R^2}{4 R^2} = \frac{\pi}{4} \approx 78.5%$.
Complexity
- Time Complexity: $\mathcal{O}(1)$ for polar inverse transform sampling (or $\mathcal{O}(1)$ expected for rejection sampling).
- Space Complexity: $\mathcal{O}(1)$.
Task 2: Longest Monotonic Ascending Sequence
Approach
Iterate through the array while maintaining two scalar variables:
current_run: the length of the strictly increasing sequence ending at the current index.max_run: the maximum length recorded so far.
If sequence[i] > sequence[i - 1], increment current_run. Otherwise, reset current_run to 1. Update max_run on each step.
Complexity
- Time Complexity: $\mathcal{O}(N)$, performing a single linear pass.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space.
Task 3: Bucket-Based Quantile Approximation
Approach
- Compute the total observations: $T = \sum \text{count}_i$.
- Compute the target cumulative sample position: $k = T \times \frac{p}{100}$.
- Traverse the bins, maintaining a running total of observations (
accumulated_count). - Find the first bin where
accumulated_count + count$\ge k$. - Perform linear interpolation within that bin: $$\text{Value} = \text{min_val} + (\text{max_val} - \text{min_val}) \times \frac{k - \text{accumulated_count}}{\text{count}}$$
- Handle empty bins ($\text{count} = 0$) by skipping them during linear search to avoid zero division.
Complexity
- Time Complexity: $\mathcal{O}(B)$ where $B$ is the number of histogram bins.
- Space Complexity: $\mathcal{O}(1)$.
Python Code Implementation
import math
import random
from typing import List, Tuple
# Task 1: Disk Point Generation
def generate_disk_point(radius: float) -> Tuple[float, float]:
theta = random.uniform(0, 2 * math.pi)
r = radius * math.sqrt(random.random())
return (r * math.cos(theta), r * math.sin(theta))
# Task 2: Longest Monotonic Ascending Sequence
def longest_ascending_run(sequence: List[int]) -> int:
if not sequence:
return 0
max_run = current_run = 1
for i in range(1, len(sequence)):
if sequence[i] > sequence[i - 1]:
current_run += 1
max_run = max(max_run, current_run)
else:
current_run = 1
return max_run
# Task 3: Bucket-Based Quantile Approximation
def approximate_percentile(bins: List[Tuple[float, float, int]], percentile: float) -> float:
if not (0 <= percentile <= 100):
raise ValueError("Percentile must be between 0 and 100.")
total_count = sum(count for _, _, count in bins)
if total_count == 0:
raise ValueError("Cannot calculate percentiles on an empty dataset.")
target_rank = total_count * (percentile / 100.0)
accumulated_count = 0
for min_val, max_val, count in bins:
if count == 0:
continue
if accumulated_count + count >= target_rank:
fraction = (target_rank - accumulated_count) / count
return min_val + (max_val - min_val) * fraction
accumulated_count += count
# Floating point precision edge-case guard for percentile = 100
for min_val, max_val, count in reversed(bins):
if count > 0:
return float(max_val)
raise RuntimeError("Invalid state reached.")