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: Calculate Total CoverageRectangle A: (-3,0) to (3,4)Area = 6×4 = 24Rectangle B: (0,-1) to (9,2)Area = 9×3 = 27Overlap: (0,0) to (3,2)Area = 3×2 = 6Total Coverage = 24 + 27 - 6 = 45AB
Understanding the Visualization
1
Input Rectangles
Two rectangles with given coordinates
2
Find Overlap
Calculate intersection area using coordinate bounds
3
Total Area
Sum both areas and subtract overlap
Key Takeaway
🎯 Key Insight: Use inclusion-exclusion principle to avoid double-counting overlapping areas
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