Leetcode 497: Random Point in Non-overlapping Rectangles

grid47
grid47
Exploring patterns and algorithms
Sep 18, 2024 6 min read

A series of non-overlapping rectangles where random points are chosen and softly illuminated as they are selected.
Solution to LeetCode 497: Random Point in Non-overlapping Rectangles Problem

You are given an array of non-overlapping axis-aligned rectangles. Each rectangle is represented by its bottom-left and top-right corner. Your task is to design a system that can pick a random integer point from the space covered by one of the given rectangles. A point on the perimeter of a rectangle is considered inside the rectangle.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of rectangles, where each rectangle is represented by its bottom-left and top-right coordinates.
Example: [[[[1, 1, 4, 4], [-2, -2, 2, 2]]]]
Constraints:
• 1 <= rects.length <= 100
• rects[i].length == 4
• -10^9 <= ai < xi <= 10^9
• -10^9 <= bi < yi <= 10^9
• xi - ai <= 2000
• yi - bi <= 2000
Output: The output should return a random integer point inside the space covered by one of the rectangles.
Example: [2, 2]
Constraints:
• The output is an array of two integers, representing the coordinates of the selected random point.
Goal: The goal is to implement a system that can select a random point from the space covered by the given rectangles, ensuring equal probability for each point.
Steps:
• 1. For each rectangle, calculate the area it covers.
• 2. Create a prefix sum array to track the cumulative area of rectangles.
• 3. Use a random number generator to select a rectangle based on its area.
• 4. Pick a random point within the selected rectangle.
Goal: The constraints for this problem are as follows.
Steps:
• The input rectangles do not overlap.
• The solution must efficiently handle up to 10^4 pick calls.
Assumptions:
• All rectangles are non-overlapping and aligned to axes.
• The selected random points should be equally likely to be chosen from any of the given rectangles.
Input: [[[[1, 1, 4, 4], [-2, -2, 2, 2]]]]
Explanation: The first rectangle covers the area from (1, 1) to (4, 4), and the second rectangle covers the area from (-2, -2) to (2, 2). The 'pick' function randomly selects a point from one of these two rectangles, such as [2, 2] or [-1, -2].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus