Area-Weighted Random Point Sampling Across Multiple Squares
Data Structure DesignModel answerLast updated
Design a class for uniform random point sampling inside a square, then extend it to sample uniformly from the union of N non-overlapping squares.
Area-Weighted Random Point Sampling Across Multiple Squares
Background
Generating uniformly distributed random points over geometric regions comes up in simulation, game development, procedural generation, and statistical testing. Getting it right requires more than picking a random shape and a random point — the selection has to be weighted by area, not by count.
Part 1: Single Square
Design a class Square that represents an axis-aligned square on the 2D plane. The square is defined by its bottom-left corner (x, y) and its side length s.
Implement a method that returns a uniformly random point (px, py) inside the square. Every point in the interior should be equally likely.
Part 2: Union of N Squares
Design a second class, SquareSampler, that takes a list of N non-overlapping Square objects and supports drawing a uniformly random point from their union.
"Uniform over the union" means: the probability that a sample falls in any region of area A is exactly A / totalArea, regardless of which square it belongs to.
Specify:
- The full API you would expose, with parameter names and return types
- The data structures used internally and why
- The step-by-step sampling algorithm
- Time and space complexity for both construction and each sample call
- How you would handle floating-point precision issues that could introduce bias
Constraints and rules
- Side lengths are non-negative. Squares with side length zero may appear in the input and should be silently ignored.
- An empty input list, or one where every square has zero area, is invalid — raise an error.
- Negative coordinates for
(x, y)are allowed; only the side length must be non-negative. - The squares are guaranteed non-overlapping. You do not need to verify this, but explain how you would handle it if you did.
- The RNG should be injectable for testability.
What the interviewer is looking for
- Correctly weighting square selection by area rather than by count (the most common bug)
- A clean two-stage sampling algorithm with justified correctness
- Awareness of floating-point edge cases that can cause out-of-bounds indexing or vanishing small squares
- A working implementation with clear complexity analysis
Hints
Hint 1
A uniform point inside a single axis-aligned square is just two independent uniform draws, one per axis. Think about why the product structure of the region makes this exact.
Hint 2
When picking which square to sample from, choosing each square with equal probability 1/N is wrong unless all squares are the same size. What probability should square i have, and how do you efficiently draw from that distribution?
Hint 3
After building prefix sums over areas and drawing a uniform random number r in [0, totalArea), you need to find which square owns r. What can r * totalArea round to, and how does that break your index lookup?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem has two independent layers. Getting each one right, and knowing where each can go wrong, is the full answer.
Part 1: Sampling inside a single square
An axis-aligned square with bottom-left corner (x, y) and side s is the Cartesian product of two intervals: [x, x+s] × [y, y+s]. Because the region factors into independent intervals, a uniform draw over it factors too: sample u1, u2 independently from Uniform[0,1) and return (x + u1·s, y + u2·s). No rejection, no trigonometry — just two RNG calls.
Part 2: Sampling from the union
Use a two-stage approach:
- Pick square
iwith probability proportional to its area:P(i) = areaᵢ / totalArea. - Sample uniformly inside square
i.
Why this is uniform over the union: for a small patch dA inside square i,
Pr(point lands in dA) = Pr(pick i) · Pr(dA | i)
= (areaᵢ / total) · (dA / areaᵢ)
= dA / total
The density is 1/total everywhere — exactly uniform. The non-overlap assumption is essential here. If squares overlapped, points in the overlap would be reachable via two different squares and their density would double.
The classic bug: picking square i uniformly at random (probability 1/N each) and then sampling inside it. This is uniform over squares, not over area. Small squares get oversampled by a factor of largeArea / smallArea. Always weight by area.
Efficient square selection: prefix sums + binary search
Precompute prefix[i] = area₀ + area₁ + … + areaᵢ. Draw r uniformly from [0, total), then binary-search for the leftmost i where prefix[i] > r. Square i owns the half-open interval [prefix[i-1], prefix[i]), which has length areaᵢ, so it gets chosen with the correct probability. Half-open intervals mean every value of r belongs to exactly one square.
API
Square(x, y, side) # immutable; raises if side < 0
Square.area() -> float
Square.sample(rng) -> (float, float)
SquareSampler(squares, rng=None) # builds prefix sums; raises if all areas are zero
SquareSampler.sample() -> (float, float)
SquareSampler.sample_many(k) -> list[(float, float)]
Key design choices: inject the RNG (deterministic tests via seed), build prefix sums once in the constructor, drop zero-area squares at construction time.
Complexity
| Operation | Time | Space |
|---|---|---|
Square.sample | O(1) | O(1) |
SquareSampler construction | O(N) | O(N) |
SquareSampler.sample | O(log N) | O(1) |
For very high sample volumes, Vose's alias method replaces the binary search with O(1) per sample after O(N) setup. It's worth mentioning as a follow-up, but prefix sums are easier to implement correctly and are the expected answer.
Floating-point hazards
This is where strong answers separate from adequate ones.
Out-of-bounds index. random() returns values in [0, 1), but r = random() * total can round up to exactly total due to floating-point rounding. bisect_right then returns index N, which is out of range. Fix: clamp the result to N - 1. The bias introduced is on the order of machine epsilon (~2⁻⁵³) and is negligible.
Accumulated summation error. Naive prefix sum accumulation drifts when areas span many orders of magnitude. Use math.fsum to compute an accurately rounded total, or better, store areas as Python integers when coordinates are integers or fixed-point. Integer arithmetic makes selection exactly unbiased.
Vanishing small squares. If a square has area 1e-20 and the running total is already 1e10, adding the small area changes nothing in floating-point: prefix[i] == prefix[i-1], and the square can never be chosen. Integer areas eliminate this. If floating-point is unavoidable, document the resolution limit: squares whose area is less than total · 2⁻⁵³ may be unreachable.
Do not recycle the selection draw. One tempting optimization rescales the leftover fraction of r within the chosen bucket and uses it as a coordinate. This degrades small squares to coarse, lattice-like coordinates. Always draw fresh uniforms for px and py.
Implementation
import bisect
import math
import random
from dataclasses import dataclass
from typing import List, Optional, Sequence, Tuple
Point = Tuple[float, float]
@dataclass(frozen=True)
class Square:
x: float
y: float
side: float
def __post_init__(self) -> None:
if self.side < 0:
raise ValueError(f"side must be non-negative, got {self.side}")
def area(self) -> float:
return self.side * self.side
def sample(self, rng: random.Random) -> Point:
return (
self.x + rng.random() * self.side,
self.y + rng.random() * self.side,
)
class SquareSampler:
"""Uniform sampling over the union of non-overlapping squares."""
def __init__(
self,
squares: Sequence[Square],
rng: Optional[random.Random] = None,
) -> None:
self._rng = rng or random.Random()
# Drop zero-area squares; they have probability 0.
self._squares: List[Square] = [s for s in squares if s.side > 0]
if not self._squares:
raise ValueError("need at least one square with positive area")
# Use integer arithmetic when sides are whole numbers for exact selection.
self._use_int = all(float(s.side).is_integer() for s in self._squares)
self._prefix: List = []
if self._use_int:
running = 0
for s in self._squares:
running += int(s.side) ** 2
self._prefix.append(running)
else:
# math.fsum gives a more accurate running total than naive addition.
partial: List[float] = []
for s in self._squares:
partial.append(s.area())
self._prefix.append(math.fsum(partial))
self._total = self._prefix[-1]
def _pick_index(self) -> int:
if self._use_int:
r = self._rng.randrange(self._total)
else:
r = self._rng.random() * self._total
idx = bisect.bisect_right(self._prefix, r)
# Clamp: floating-point rounding can push r exactly to total.
return min(idx, len(self._squares) - 1)
def sample(self) -> Point:
return self._squares[self._pick_index()].sample(self._rng)
def sample_many(self, k: int) -> List[Point]:
return [self.sample() for _ in range(k)]
Edge cases to call out
- All squares have zero side length →
ValueErrorat construction. - A single square → degenerates correctly to
Square.sample. - Negative
(x, y)→ works unchanged; onlysideis constrained. - Overlapping squares violate the precondition. To validate, run a sweep-line algorithm in O(N log N). To handle, decompose the union into disjoint pieces first — mention this but don't implement it unless asked.