Program to find total area covered by two rectangles in Python

When two rectangles overlap in a 2D plane, we need to calculate their total covered area by finding the sum of both areas minus any overlapping region. Each rectangle is defined by its bottom-left corner (x1, y1) and top-right corner (x2, y2).

Rectangle 1 (A,B) (C,D) Rectangle 2 (E,F) (G,H) Overlap

Algorithm

To solve this problem, we follow these steps −

  • Calculate area of first rectangle: width_1 * height_1
  • Calculate area of second rectangle: width_2 * height_2
  • Find total area: area_1 + area_2
  • Check if rectangles overlap using boundary conditions
  • If they overlap, subtract the overlapping area from total

Implementation

def solve(A, B, C, D, E, F, G, H):
    # Calculate dimensions and areas of both rectangles
    width_1 = abs(C - A)
    height_1 = abs(D - B)
    
    width_2 = abs(G - E)
    height_2 = abs(H - F)
    
    area = width_1 * height_1 + width_2 * height_2
    
    # Check if rectangles don't overlap
    if (G < A) or (E > C) or (F > D) or (H < B):
        return area
    else:
        # Calculate overlapping region
        p = max(A, E)  # Left boundary of overlap
        q = max(B, F)  # Bottom boundary of overlap
        r = min(C, G)  # Right boundary of overlap
        s = min(D, H)  # Top boundary of overlap
        
        width_3 = abs(r - p)
        height_3 = abs(s - q)
        
        return area - (width_3 * height_3)

# Example coordinates
A, B = -3, 0   # Rectangle 1: bottom-left
C, D = 3, 4    # Rectangle 1: top-right
E, F = 0, -1   # Rectangle 2: bottom-left
G, H = 9, 2    # Rectangle 2: top-right

result = solve(A, B, C, D, E, F, G, H)
print(f"Total area covered: {result}")
Total area covered: 45

How It Works

The algorithm calculates:

  • Rectangle 1 area: |3 - (-3)| * |4 - 0| = 6 * 4 = 24
  • Rectangle 2 area: |9 - 0| * |2 - (-1)| = 9 * 3 = 27
  • Total without overlap: 24 + 27 = 51
  • Overlap area: |3 - 0| * |2 - 0| = 3 * 2 = 6
  • Final result: 51 - 6 = 45

Edge Cases

# Case 1: No overlap
print("No overlap:", solve(0, 0, 2, 2, 5, 0, 7, 2))

# Case 2: Complete overlap (one inside another)
print("Complete overlap:", solve(0, 0, 6, 6, 2, 2, 4, 4))

# Case 3: Adjacent rectangles (touching edges)
print("Adjacent rectangles:", solve(0, 0, 2, 2, 2, 0, 4, 2))
No overlap: 8
Complete overlap: 32
Adjacent rectangles: 8

Conclusion

This algorithm efficiently calculates the total area covered by two rectangles by summing individual areas and subtracting any overlap. The key is properly detecting overlap using boundary conditions and calculating the intersection dimensions.

Updated on: 2026-03-26T18:20:09+05:30

427 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements