Rectangle Area - Problem

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.

The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).

The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).

Note: The total area is the sum of areas of both rectangles minus any overlapping area between them.

Input & Output

Example 1 — Overlapping Rectangles
$ Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
Output: 45
💡 Note: Rectangle A has area (3-(-3)) × (4-0) = 6×4 = 24. Rectangle B has area (9-0) × (2-(-1)) = 9×3 = 27. Overlap from x=0 to x=3 and y=0 to y=2 has area 3×2 = 6. Total: 24 + 27 - 6 = 45
Example 2 — No Overlap
$ Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = 3, by1 = 3, bx2 = 4, by2 = 4
Output: 17
💡 Note: Rectangle A has area 4×4 = 16. Rectangle B has area 1×1 = 1. No overlap since rectangles are completely separate. Total: 16 + 1 = 17
Example 3 — One Inside Another
$ Input: ax1 = 0, ay1 = 0, ax2 = 10, ay2 = 10, bx1 = 2, by1 = 2, bx2 = 8, by2 = 8
Output: 100
💡 Note: Rectangle A has area 10×10 = 100. Rectangle B has area 6×6 = 36. B is completely inside A, so overlap = 36. Total: 100 + 36 - 36 = 100

Constraints

  • -104 ≤ ax1 < ax2 ≤ 104
  • -104 ≤ ay1 < ay2 ≤ 104
  • -104 ≤ bx1 < bx2 ≤ 104
  • -104 ≤ by1 < by2 ≤ 104

Visualization

Tap to expand
Rectangle Area Problem INPUT Rect A Rect B Rectangle A: ax1=-3, ay1=0 ax2=3, ay2=4 Rectangle B: bx1=0, by1=-1 bx2=9, by2=2 Overlap shown in purple ALGORITHM STEPS 1 Calculate Area A (3-(-3)) * (4-0) = 24 2 Calculate Area B (9-0) * (2-(-1)) = 27 3 Find Overlap overlapX = min(ax2,bx2)-max(ax1,bx1) = min(3,9)-max(-3,0) = 3 overlapY = min(ay2,by2)-max(ay1,by1) = min(4,2)-max(0,-1) = 2 Overlap Area = 3 * 2 = 6 4 Total Area Formula Total = A + B - Overlap Total = 24 + 27 - 6 = 45 24 + 27 - 6 = 45 FINAL RESULT Total Coverage Visualization A=24 B=27 -6 Overlap counted once, not twice Subtract overlap from sum OUTPUT 45 OK - Verified 24 + 27 - 6 = 45 Key Insight: When two rectangles overlap, simply adding their areas counts the overlap region twice. The overlap dimensions are found using: max(left edges) to min(right edges) for width, and max(bottom edges) to min(top edges) for height. If either is negative, no overlap exists. TutorialsPoint - Rectangle Area | Optimal Solution Time: O(1) | Space: O(1)
Asked in
Google 25 Amazon 18 Microsoft 12 Apple 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 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