Skip to main content

Rectangle Area

Medium Subject: Math & Geometry
Time Complexity
O(1)
Space Complexity
O(1)

Problem Description

Problem Statement

Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles. Rectangle 1 is defined by (ax1, ay1, ax2, ay2), and Rectangle 2 by (bx1, by1, bx2, by2).

Example 1:

  • Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
  • Output: 45

Optimal Solution

Python

Approach: Area Sum minus Overlap

Calculate the area of both rectangles individually. If they overlap, calculate the overlap width as min(ax2, bx2) - max(ax1, bx1) and height as min(ay2, by2) - max(ay1, by1). If width or height is negative, there is no overlap. Subtract the overlap area from the sum.

class Solution:
    def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int:
        area1 = (ax2 - ax1) * (ay2 - ay1)
        area2 = (bx2 - bx1) * (by2 - by1)

        overlap_width = min(ax2, bx2) - max(ax1, bx1)
        overlap_height = min(ay2, by2) - max(ay1, by1)

        overlap_area = 0
        if overlap_width > 0 and overlap_height > 0:
            overlap_area = overlap_width * overlap_height

        return area1 + area2 - overlap_area