Rectangles Area - Problem

Given a Points table containing 2D coordinates, find all possible axis-aligned rectangles with non-zero area that can be formed by any two points.

Table Schema:

  • id (int): Unique identifier for each point
  • x_value (int): X coordinate of the point
  • y_value (int): Y coordinate of the point

Requirements:

  • Each row should contain p1, p2 (point IDs), and area
  • Only include rectangles with non-zero area
  • Order by area DESC, then p1 ASC, then p2 ASC

Table Schema

Points
Column Name Type Description
id PK int Unique identifier for each point
x_value int X coordinate of the point
y_value int Y coordinate of the point
Primary Key: id
Note: Each point represents a 2D coordinate (x_value, y_value)

Input & Output

Example 1 — Basic Rectangle Formation
Input Table:
id x_value y_value
1 1 1
2 3 3
3 2 4
Output:
p1 p2 area
1 2 4
1 3 3
2 3 1
💡 Note:

Points (1,1), (3,3), and (2,4) form rectangles with areas: Point 1 to 3: |1-2|×|1-4| = 6, Point 1 to 2: |1-3|×|1-3| = 4, Point 2 to 3: |3-2|×|3-4| = 1. Results ordered by area descending.

Example 2 — Points with Same Coordinates
Input Table:
id x_value y_value
1 1 1
2 1 2
3 2 1
Output:
p1 p2 area
2 3 1
💡 Note:

No rectangles can be formed because no two points have both different x_value AND different y_value coordinates. Points sharing the same x or y coordinate cannot form rectangles with non-zero area.

Example 3 — Single Valid Rectangle
Input Table:
id x_value y_value
1 0 0
2 3 4
Output:
p1 p2 area
1 2 12
💡 Note:

Points (0,0) and (3,4) form one rectangle with area = |0-3| × |0-4| = 3 × 4 = 12.

Constraints

  • 1 ≤ Points table rows ≤ 500
  • -10^6 ≤ x_value, y_value ≤ 10^6
  • All id values are unique

Visualization

Tap to expand
Rectangles Area - SQL Problem INPUT Points Table id x y P1 -1 -1 P2 2 2 P3 -1 2 P4 2 -1 2D Coordinate View P1 P2 P3 P4 ALGORITHM STEPS 1 Self Join Points Join table with itself to get point pairs 2 Filter Conditions p1.id < p2.id AND p1.x != p2.x AND p1.y != p2.y 3 Calculate Area ABS(p2.x - p1.x) * ABS(p2.y - p1.y) 4 Order Results ORDER BY area DESC, p1 ASC, p2 ASC SELECT p1.id, p2.id, ABS(p2.x-p1.x) * ABS(p2.y-p1.y) AS area FROM Points p1, Points p2 WHERE p1.id < p2.id ... FINAL RESULT Output Table p1 p2 area P1 P2 9 P1 P4 9 P3 P4 9 Rectangle Formed Width: 3 units Height: 3 units Area = 3 x 3 = 9 OK - Valid Key Insight: For axis-aligned rectangles, two diagonal points fully define the rectangle. The self-join finds all point pairs, filtering ensures different x AND y coordinates (non-zero area). Area = |x2-x1| * |y2-y1|. Using p1.id < p2.id avoids duplicate pairs and ensures consistent ordering of results. TutorialsPoint - Rectangles Area | Optimal Solution
Asked in
Amazon 15 Microsoft 8
12.5K Views
Medium Frequency
~20 min Avg. Time
285 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen