Problem Description
Given an array of rectangles where each rectangle is represented by [length, height] and all rectangles are anchored at (0, 0), along with an array of points [x, y], determine for each point the number of rectangles that contain it. A rectangle contains a point if and only if 0 <= x <= length and 0 <= y <= height.
Key Insights
- The y-coordinate of rectangles (height) is limited (1 <= height <= 100) even though the length can be as large as 10^9.
- You can group rectangles by their height which allows processing queries by iterating only over heights that are large enough.
- For rectangles with a given height, store their lengths in a sorted list so that binary search can be used to count how many rectangles have length >= x for a given point.
- For each query point (x, y), iterate over all possible heights from y up to 100 and use binary search to quickly count the qualified rectangles.
Space and Time Complexity
Time Complexity: O(P * H * log(R/H)) where P is the number of points, H is the maximum height (bounded by 100) and R/H is the average number of rectangles per height group. Space Complexity: O(R) for storing the rectangle lengths grouped by height.
Solution
The strategy is to preprocess the input rectangles by grouping them based on their heights. For each height, we maintain a sorted list of the corresponding rectangle lengths. When processing a point (x, y), we consider every rectangle group with height >= y and perform a binary search on the sorted list to count how many rectangle lengths are >= x. By summing the counts over these groups, we obtain the total number of rectangles containing that point. This approach leverages the relatively small range of possible heights to reduce unnecessary work compared to scanning all rectangles for every point.