Leetcode 2250: Count Number of Rectangles Containing Each Point

grid47
grid47
Exploring patterns and algorithms
Mar 27, 2024 6 min read

You are given a 2D integer array rectangles, where each element rectangles[i] = [li, hi] represents a rectangle with a bottom-left corner at (0, 0), a length li, and a height hi. Additionally, you are provided a 2D integer array points, where each element points[j] = [xj, yj] represents a point on a 2D plane. The task is to determine the number of rectangles that contain each point. A rectangle contains a point if the point satisfies 0 <= xj <= li and 0 <= yj <= hi. Points on the edges of rectangles are also considered to be inside.
Problem
Approach
Steps
Complexity
Input: The input consists of a list of rectangles and a list of points.
Example: rectangles = [[2, 3], [3, 4], [4, 5]], points = [[2, 2], [1, 4]]
Constraints:
• 1 <= rectangles.length, points.length <= 5 * 10^4
• rectangles[i].length == points[j].length == 2
• 1 <= li, xj <= 10^9
• 1 <= hi, yj <= 100
• All rectangles and points are unique.
Output: Return an integer array where each element corresponds to the number of rectangles that contain the respective point.
Example: Output: [3, 2]
Constraints:
Goal: For each point, count the number of rectangles that contain it by comparing its coordinates against the dimensions of each rectangle.
Steps:
• Sort the rectangles by their lengths.
• Group rectangles by their heights to optimize search operations.
• For each point, iterate over possible rectangle groups based on the point's height and check if the point's x-coordinate lies within the rectangle's length.
• Use binary search to efficiently count rectangles that meet the conditions.
Goal: Ensure efficient processing of up to 50,000 rectangles and points while adhering to the given range constraints.
Steps:
• Rectangles and points are unique.
• Height values of rectangles are bounded by 100.
Assumptions:
• All rectangles are axis-aligned and start from the origin.
• The number of rectangles and points may vary independently.
Input: rectangles = [[3, 2], [4, 3]], points = [[2, 2], [3, 1]]
Explanation: The point (2, 2) is contained by both rectangles, while the point (3, 1) is contained only by the second rectangle. Thus, the result is [2, 1].

Input: rectangles = [[1, 1], [2, 2], [3, 3]], points = [[2, 3], [1, 1]]
Explanation: The point (2, 3) is contained only by the third rectangle, while the point (1, 1) is contained by all three rectangles. Thus, the result is [1, 3].

Link to LeetCode Lab


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