Problem Description
Given n distinct points on a 2D-plane, assign one person to each point. Among these people are Alice and Bob. Alice will try to build a rectangular fence with her position as the upper left corner and Bob’s position as the lower right corner. The fence (including its boundary) must not contain any of the other people. Return the number of valid pairs of points (Alice, Bob) where the placement meets the following conditions:
- Alice’s x-coordinate is less than or equal to Bob’s x-coordinate.
- Alice’s y-coordinate is greater than or equal to Bob’s y-coordinate.
- No other point lies inside or on the boundary of the rectangle determined by Alice’s and Bob’s positions.
Key Insights
- For a candidate pair (A, B), the rectangle is defined with A’s position as the top-left corner and B’s as the bottom-right.
- The valid configuration requires A.x <= B.x and A.y >= B.y.
- Any other point inside or on the perimeter of the rectangle invalidates the placement.
- By “compressing” coordinates (since there are at most 1000 points), we can build a grid where each cell indicates whether a point is present.
- With a 2D prefix sum (cumulative frequency grid) on the compressed grid, we can efficiently query the number of points inside any axis-aligned rectangle.
- Finally, iterate through all valid pairs (A, B) (O(n^2)) and use the prefix sum to check that exactly two points are present (A and B themselves) within the defined rectangle.
Space and Time Complexity
Time Complexity: O(n^2 + G) where n is the number of points and G is the number of cells (at most O(n^2)) to compute the prefix sum grid. In worst-case, it is approximately O(n^2).
Space Complexity: O(n^2) for the compressed grid and its prefix sum.
Solution
We first compress the x and y coordinates to create a small grid (since the points are sparse but coordinates can be very large). Then we build a 2D grid with 1’s marking where points exist. We compute a 2D prefix sum over this grid so that any axis-aligned subrectangle can be queried in constant time. For every pair of points that satisfy the ordering conditions for being top‐left and bottom‐right, we query the count of points in the corresponding rectangle. If the count equals 2 (only the pair of points itself), we count this pair as valid.
The solution uses coordinate compression, a 2D prefix sum data structure, and a brute-force check over all candidate pairs with the prefix sum query as the “trick” to bring down the query time.