Rectangles Area Problem
#1459
Description
LeetCode Problem 1459.
Table: Points
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| x_value | int |
| y_value | int |
+---------------+---------+
id is the primary key for this table.
Each point is represented as a 2D Dimensional (x_value, y_value).
Write an SQL query to report of all possible rectangles which can be formed by any two points of the table.
Each row in the result contains three columns (p1, p2, area) where:
- p1 and p2 are the id of two opposite corners of a rectangle and p1 < p2.
- Area of this rectangle is represented by the column area.
Report the query in descending order by area in case of tie in ascending order by p1 and p2.
Points table:
+----------+-------------+-------------+
| id | x_value | y_value |
+----------+-------------+-------------+
| 1 | 2 | 8 |
| 2 | 4 | 7 |
| 3 | 2 | 10 |
+----------+-------------+-------------+
Result table:
+----------+-------------+-------------+
| p1 | p2 | area |
+----------+-------------+-------------+
| 2 | 3 | 6 |
| 1 | 2 | 2 |
+----------+-------------+-------------+
p1 should be less than p2 and area greater than 0.
p1 = 1 and p2 = 2, has an area equal to |2-4| * |8-7| = 2.
p1 = 2 and p2 = 3, has an area equal to |4-2| * |7-10| = 6.
p1 = 1 and p2 = 3 It's not possible because the rectangle has an area equal to 0.
Solution
Approach: Self Join on Pairs of Points
Any two points can be opposite corners of a rectangle whose sides are parallel to the axes. Its width is |x1 - x2| and its height is |y1 - y2|, so the area is their product.
- Each pair once. Join
Pointsto itself witha.id < b.id. This skips pairing a point with itself, and it lists each pair only once, already in the requiredp1 < p2form. - Real rectangles only. If the two points share an
x_valueor ay_value, one side has length 0 and the "rectangle" is a line with area 0, like points 1 and 3. Requiring differentxand differentyremoves those pairs. - Order.
ORDER BY area DESC, p1, p2: largest area first, ties byp1thenp2. In the test data, pairs(2, 3)and(3, 4)both have area 6, sop1decides.
The Pandas version builds all pairs with a cross merge, keeps id_a < id_b, computes the area, drops areas of 0 and sorts by the same three keys.
SELECT a.id AS p1,
b.id AS p2,
ABS(a.x_value - b.x_value) * ABS(a.y_value - b.y_value) AS area
FROM Points AS a
JOIN Points AS b
ON a.id < b.id
-- Same x or same y: the rectangle would be flat (area 0).
WHERE a.x_value <> b.x_value
AND a.y_value <> b.y_value
ORDER BY area DESC, p1, p2;