Magicsheet logo

Rectangles Area

Medium
89.4%
Updated 6/1/2025

Asked by 2 Companies

Topics

Rectangles Area

What is this problem about?

The Rectangles Area SQL problem asks you to compute the area of each rectangle defined by (p1, q1) and (p2, q2) coordinate pairs, filtering out degenerate cases (area = 0). Return only non-zero area rectangles with their computed area. The database interview pattern demonstrates computed column SQL.

Why is this asked in interviews?

Twitter/X asks this to test SQL arithmetic on coordinate data — computing (abs(p2-p1) × abs(q2-q1)) with a non-zero filter. It validates basic SQL math operations and WHERE clause filtering.

Algorithmic pattern used

Computed column + filter.

SELECT p1, q1, p2, q2, ABS(p2-p1) * ABS(q2-q1) AS area
FROM Rectangle
WHERE ABS(p2-p1) * ABS(q2-q1) > 0
ORDER BY area DESC

Or equivalently: WHERE p1 <> p2 AND q1 <> q2.

Example explanation

Row (0,0,2,3): area=2*3=6. Row (0,0,1,1): area=1. Row (0,0,0,5): area=0 (degenerate — same x). Exclude last row.

Common mistakes candidates make

  • Not filtering zero-area rectangles (points or line segments).
  • Using (p2-p1)*(q2-q1) without ABS (negative coordinates cause wrong area).
  • Not ordering by area (if required by the problem).
  • Using HAVING instead of WHERE for non-aggregate filtering.

Interview preparation tip

SQL arithmetic problems require wrapping coordinate differences in ABS() to handle negative coordinate differences. The zero-area filter can use either WHERE area > 0 or WHERE p1 <> p2 AND q1 <> q2. Practice similar "computed geometry SQL" problems: "compute distances between points," "compute polygon areas from vertex tables."

Similar Questions