Rectangle Area - Problem
Rectangle Area Calculator - A Geometric Challenge

Imagine you're designing a floor plan application where users can place rectangular carpets on a floor. Sometimes these carpets overlap, and you need to calculate the total area covered by both carpets combined.

Given two rectangles in a 2D coordinate system, your task is to find the total area covered by both rectangles. Each rectangle is defined by:
โ€ข Bottom-left corner: (x1, y1)
โ€ข Top-right corner: (x2, y2)

The key challenge is handling overlapping regions - you should count overlapped areas only once!

Input: 8 integers representing coordinates of two rectangles
Output: Single integer representing the total covered area

Rectangle A: (ax1, ay1) to (ax2, ay2)
Rectangle B: (bx1, by1) to (bx2, by2)

Input & Output

example_1.py โ€” Basic Overlap
$ 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) = 24. Rectangle B has area (9-0)*(2-(-1)) = 27. Overlap area is (3-0)*(2-0) = 6. Total = 24 + 27 - 6 = 45.
example_2.py โ€” No Overlap
$ Input: ax1=-2, ay1=-2, ax2=2, by2=2, bx1=3, by1=3, bx2=7, by2=7
โ€บ Output: 32
๐Ÿ’ก Note: Rectangle A has area 4*4 = 16. Rectangle B has area 4*4 = 16. No overlap since rectangles don't intersect. Total = 16 + 16 - 0 = 32.
example_3.py โ€” Complete Overlap
$ Input: ax1=0, ay1=0, ax2=4, ay2=4, bx1=1, by1=1, bx2=3, by2=3
โ€บ Output: 16
๐Ÿ’ก Note: Rectangle A has area 4*4 = 16. Rectangle B has area 2*2 = 4. Rectangle B is completely inside A, so overlap = 4. Total = 16 + 4 - 4 = 16.

Constraints

  • -104 โ‰ค ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 โ‰ค 104
  • ax1 < ax2 and ay1 < ay2 (Rectangle A is valid)
  • bx1 < bx2 and by1 < by2 (Rectangle B is valid)
  • All coordinates are integers

Visualization

Tap to expand
Rectangle Area Coverage ProblemCarpet AArea = 200 ร— 120 = 24,000Carpet BArea = 160 ร— 100 = 16,000Overlap70 ร— 70 = 4,900Calculation Steps1. Area A = 24,0002. Area B = 16,0003. Overlap = 4,900Total = 24,000 + 16,000 - 4,900= 35,100 square units
Understanding the Visualization
1
Measure Each Carpet
Calculate the area of each rectangular carpet individually using length ร— width
2
Find Overlap Region
Determine where the carpets overlap by finding intersection boundaries
3
Apply Inclusion-Exclusion
Total covered area = Carpet A area + Carpet B area - Overlapped area
Key Takeaway
๐ŸŽฏ Key Insight: Use inclusion-exclusion principle to avoid double-counting overlapped areas when calculating total coverage of geometric shapes.
Asked in
Google 45 Microsoft 35 Amazon 28 Meta 22
67.0K Views
Medium Frequency
~15 min Avg. Time
1.5K 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