Random Point in Non-overlapping Rectangles - Problem
You are given an array of non-overlapping axis-aligned rectangles rects where rects[i] = [ai, bi, xi, yi] indicates that (ai, bi) is the bottom-left corner point of the ith rectangle and (xi, yi) is the top-right corner point of the ith rectangle.
Design an algorithm to pick a random integer point inside the space covered by one of the given rectangles. A point on the perimeter of a rectangle is included in the space covered by the rectangle.
Any integer point inside the space covered by one of the given rectangles should be equally likely to be returned.
Note: An integer point is a point that has integer coordinates.
Implement the Solution class:
Solution(int[][] rects)Initializes the object with the given rectanglesrects.int[] pick()Returns a random integer point[u, v]inside the space covered by one of the given rectangles.
Input & Output
Example 1 — Single Rectangle
$
Input:
rects = [[-2,-2,1,1]]
›
Output:
[0,-1] (one possible answer)
💡 Note:
Single rectangle from (-2,-2) to (1,1). Any point within this rectangle is valid, such as (0,-1).
Example 2 — Multiple Rectangles
$
Input:
rects = [[-2,-2,-1,-1], [1,0,3,2]]
›
Output:
[2,1] (one possible answer)
💡 Note:
First rectangle has area 1, second has area 6. Point selection should be weighted by area, so second rectangle is 6 times more likely to be chosen.
Example 3 — Equal Area Rectangles
$
Input:
rects = [[0,0,1,1], [2,2,3,3]]
›
Output:
[3,3] (one possible answer)
💡 Note:
Both rectangles have equal area (4 points each), so each rectangle should be selected with equal probability.
Constraints
- 1 ≤ rects.length ≤ 100
- rects[i].length == 4
- -109 ≤ ai < xi ≤ 109
- -109 ≤ bi < yi ≤ 109
- xi - ai ≤ 2000
- yi - bi ≤ 2000
Visualization
Tap to expand
Understanding the Visualization
1
Input Rectangles
Multiple non-overlapping rectangles with different sizes
2
Area-Weighted Selection
Select rectangle proportional to its area
3
Random Point
Pick random coordinates within selected rectangle
Key Takeaway
🎯 Key Insight: Weight rectangle selection by area to achieve uniform point distribution across all rectangles
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code