223. Rectangle Area

  • Math
  • Geometry
TIME
O(1)
SPACE
O(1)
problem on leetcode ↗source on github ↗

Intuition

Total area covered = Area of rectangle A + Area of rectangle B - Overlapping area (to avoid double counting).

Solution

  1. Calculate individual areas: Compute area of each rectangle using width × height.

  2. Find intersection bounds:

    • left = max(ax1, bx1)
    • right = min(ax2, bx2)
    • bottom = max(ay1, by1)
    • top = min(ay2, by2)
  3. Calculate intersection area:

    • If right > left and top > bottom, intersection exists
    • Intersection area = (right - left) × (top - bottom)
    • Otherwise, intersection area = 0
  4. Return total: areaA + areaB - intersectionArea

Complexity

  • Time: O(1), constant arithmetic operations
  • Space: O(1), no extra space

Edge Cases

  • Rectangles don't overlap → intersection area is 0
  • One rectangle inside another → intersection is the smaller rectangle
  • Rectangles are identical → result is area of one rectangle
  • Rectangles touch at edge/corner → intersection area is 0 (no overlap)

Code

class Solution:
    def computeArea(
        self, ax1: int, ay1: int, ax2: int, ay2: int, 
        bx1: int, by1: int, bx2: int, by2: int
    ) -> int:
        """
        223. Rectangle Area
        Time: O(1)
        Space: O(1)
        """
        total_area = ((ax2 - ax1) * (ay2 - ay1)) + ((bx2 - bx1) * (by2 - by1))
        
        intersected_left = max(ax1, bx1)
        intersected_right = min(ax2, bx2)
        intersected_horizontal = intersected_right - intersected_left if intersected_right > intersected_left else 0
        
        intersected_bottom = max(ay1, by1)
        intersected_top = min(ay2, by2)
        intersected_vertical = intersected_top - intersected_bottom if intersected_top > intersected_bottom else 0
        
        intersected_area = intersected_horizontal * intersected_vertical
        
        return total_area - intersected_area