914. Random Point in Non-overlapping Rectangles
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to design an algorithm that can randomly pick an integer point from a set of non-overlapping, axis-aligned rectangles. The crucial requirement is that every single integer point within the union of these rectangles must have an equal probability of being selected.
Solution
Random Point in Non-overlapping Rectangles in Python
import random
import bisect
class Solution:
def __init__(self, rects: list[list[int]]):
self.rects = rects
self.prefix_sum = []
current_sum = 0
for x1, y1, x2, y2 in rects:
# Number of points in the rectangle is (x2 - x1 + 1) * (y2 - y1 + 1)
# as coordinates are inclusive.
# Python's integers handle arbitrary size, so no overflow issues.
points = (x2 - x1 + 1) * (y2 - y1 + 1)
current_sum += points
self.prefix_sum.append(current_sum)
self.total_points = current_sum
def pick(self) -> list[int]:
# Generate a random integer from 1 to total_points (inclusive).
target = random.randint(1, self.total_points)
# Use binary search (bisect_left) to find the index of the rectangle.
# bisect_left finds the first index i where prefix_sum[i] >= target.
rect_idx = bisect.bisect_left(self.prefix_sum, target)
# Get the chosen rectangle's coordinates.
x1, y1, x2, y2 = self.rects[rect_idx]
# Determine the number of points in all preceding rectangles.
prev_points = self.prefix_sum[rect_idx - 1] if rect_idx > 0 else 0
# Find the specific point's index within the current rectangle (0-based).
point_idx = target - prev_points - 1
# Width of the rectangle in terms of number of integer points.
width = x2 - x1 + 1
# Calculate coordinates by mapping the 1D index to 2D.
px = x1 + point_idx % width
py = y1 + point_idx // width
return [px, py]
# Your Solution object will be instantiated and called as such:
# obj = Solution(rects)
# param_1 = obj.pick()
Random Point in Non-overlapping Rectangles in Java
class Solution {
private int[][] rects;
private long[] prefix_sum;
private long total_points;
public Solution(int[][] rects) {
this.rects = rects;
this.prefix_sum = new long[rects.length];
long current_sum = 0;
for (int i = 0; i < rects.length; i++) {
int[] r = rects[i];
// Number of points in rectangle [x1, y1, x2, y2]
// is (x2 - x1 + 1) * (y2 - y1 + 1).
// Use long to prevent potential overflow.
current_sum += (long)(r[2] - r[0] + 1) * (r[3] - r[1] + 1);
this.prefix_sum[i] = current_sum;
}
this.total_points = current_sum;
}
public int[] pick() {
// Generate a random long from 1 to total_points (inclusive).
// ThreadLocalRandom is efficient and safe for concurrent use.
long target = java.util.concurrent.ThreadLocalRandom.current().nextLong(1, total_points + 1);
// Binary search to find which rectangle this point falls into.
int low = 0, high = prefix_sum.length - 1;
int rect_idx = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
if (target <= prefix_sum[mid]) {
rect_idx = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
// Get the chosen rectangle's coordinates.
int[] r = rects[rect_idx];
int x1 = r[0], y1 = r[1], x2 = r[2];
// Determine the number of points in all preceding rectangles.
long prev_points = (rect_idx > 0) ? prefix_sum[rect_idx - 1] : 0;
// Find the specific point's index within the current rectangle (0-based).
long point_idx = target - prev_points - 1;
// Width of the rectangle in terms of number of integer points.
int width = x2 - x1 + 1;
// Calculate coordinates by mapping the 1D index to 2D.
int px = x1 + (int)(point_idx % width);
int py = y1 + (int)(point_idx / width);
return new int[]{px, py};
}
}
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(rects);
* int[] param_1 = obj.pick();
*/
Random Point in Non-overlapping Rectangles in C++
class Solution {
private:
std::vector<std::vector<int>> rects;
std::vector<long long> prefix_sum;
long long total_points;
std::mt19937 gen; // Mersenne Twister engine for random numbers
std::uniform_int_distribution<long long> distrib;
public:
Solution(std::vector<std::vector<int>>& rects) {
this->rects = rects;
long long current_sum = 0;
for (const auto& r : rects) {
// Number of points in rectangle [x1, y1, x2, y2]
// is (x2 - x1 + 1) * (y2 - y1 + 1).
// Use long long to prevent potential overflow.
current_sum += (long long)(r[2] - r[0] + 1) * (r[3] - r[1] + 1);
this->prefix_sum.push_back(current_sum);
}
this->total_points = current_sum;
// Initialize the random number generator.
std::random_device rd;
this->gen = std::mt19937(rd());
if (total_points > 0) {
this->distrib = std::uniform_int_distribution<long long>(1, total_points);
}
}
std::vector<int> pick() {
// Generate a random integer from 1 to total_points.
long long target = distrib(gen);
// Binary search to find which rectangle this point falls into.
// std::lower_bound finds the first element not less than target.
auto it = std::lower_bound(prefix_sum.begin(), prefix_sum.end(), target);
int rect_idx = std::distance(prefix_sum.begin(), it);
// Get the chosen rectangle's coordinates.
const auto& r = rects[rect_idx];
int x1 = r[0], y1 = r[1], x2 = r[2];
// Determine the number of points in all preceding rectangles.
long long prev_points = (rect_idx > 0) ? prefix_sum[rect_idx - 1] : 0;
// Find the specific point's index within the current rectangle (0-based).
long long point_idx = target - prev_points - 1;
// Width of the rectangle in terms of number of integer points.
int width = x2 - x1 + 1;
// Calculate coordinates by mapping the 1D index to 2D.
int px = x1 + (int)(point_idx % width);
int py = y1 + (int)(point_idx / width);
return {px, py};
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(rects);
* vector<int> param_1 = obj->pick();
*/
Random Point in Non-overlapping Rectangles in TypeScript
class Solution {
private rects: number[][];
private prefixSum: number[];
private totalPoints: number;
constructor(rects: number[][]) {
this.rects = rects;
this.prefixSum = [];
let currentSum = 0;
for (const r of rects) {
// Number of points in rectangle [x1, y1, x2, y2]
// is (x2 - x1 + 1) * (y2 - y1 + 1).
// JavaScript numbers are 64-bit floats, safe up to 2^53.
// Max total points is ~4*10^8, which is well within the safe range.
currentSum += (r[2] - r[0] + 1) * (r[3] - r[1] + 1);
this.prefixSum.push(currentSum);
}
this.totalPoints = currentSum;
}
pick(): number[] {
// Generate a random integer from 1 to totalPoints (inclusive).
const target = Math.floor(Math.random() * this.totalPoints) + 1;
// Binary search to find which rectangle this point falls into.
let low = 0, high = this.rects.length - 1;
let rectIdx = -1;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
if (target <= this.prefixSum[mid]) {
rectIdx = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
// Get the chosen rectangle's coordinates.
const [x1, y1, x2, y2] = this.rects[rectIdx];
// Determine the number of points in all preceding rectangles.
const prevPoints = rectIdx > 0 ? this.prefixSum[rectIdx - 1] : 0;
// Find the specific point's index within the current rectangle (0-based).
const pointIdx = target - prevPoints - 1;
// Width of the rectangle in terms of number of integer points.
const width = x2 - x1 + 1;
// Calculate coordinates by mapping the 1D index to 2D.
const px = x1 + pointIdx % width;
const py = y1 + Math.floor(pointIdx / width);
return [px, py];
}
}
/**
* Your Solution object will be instantiated and called as such:
* var obj = new Solution(rects)
* var param_1 = obj.pick()
*/
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.