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 rectangles rects.
  • 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
Random Point in Non-overlapping RectanglesRect ARect BRect CArea: 8000Area: 15000Area: 3600Selected Point1. Weight selection by area: P(B) = 15000/26600 ≈ 56%2. Rectangle B selected (highest probability)3. Random point generated within Rectangle BResult: Uniform distribution across all rectangles
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
Asked in
Google 15 Facebook 8 Amazon 6
28.5K Views
Medium Frequency
~25 min Avg. Time
842 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen