Problem
Table: Points
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| x_value | int |
| y_value | int |
+---------------+---------+
id is the column with unique values for this table.
Each point is represented as a 2D coordinate (x_value, y_value).
Write a solution to report all possible axis-aligned rectangles with a
non-zero area that can be formed by any two points from the Points
table.
Each row in the result should contain three columns (p1, p2, area)
where:
p1
andp2
are theid
’s of the two points that determine the opposite corners of a rectangle.area
is the area of the rectangle and must be non-zero.
Return the result table ordered by area
in descending order. If there is a tie, order them by p1
in ascending order. If there is still a tie, order them by p2
in ascending order.
The result format is in the following table.
Examples
Example 1:
|
|
Solution
Method 1 – Self Join and Area Calculation
Intuition
For every pair of points, if their x and y values are both different, they can form the diagonal of an axis-aligned rectangle. The area is the product of the absolute differences of their x and y values.
Approach
- Join the table with itself to get all pairs of points (p1, p2) with p1.id < p2.id.
- For each pair, check that both x and y values are different.
- Compute the area as |x1 - x2| * |y1 - y2|.
- Filter out pairs with area 0.
- Order by area descending, then p1 ascending, then p2 ascending.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
, where n is the number of points, since we check all pairs. - 🧺 Space complexity:
O(k)
, where k is the number of valid rectangle pairs (output size).