We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Rectangle Area

Number: 223

Difficulty: Medium

Paid? No

Companies: Microsoft, Google, Nvidia, Meta


Problem Description

Given the coordinates of two rectilinear rectangles in a 2D plane, compute the total area covered by the two rectangles. Each rectangle is defined by the coordinates of its bottom-left and top-right corners.


Key Insights

  • Calculate the area of each rectangle separately.
  • Determine whether the two rectangles overlap.
  • If they overlap, compute the overlapping region's dimensions.
  • Subtract the overlapping area once from the combined area of both rectangles to avoid double-counting.
  • Use max and min functions to derive the boundaries of the overlapping region.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

The solution first calculates the area of each rectangle using the formula: area = (x2 - x1) * (y2 - y1).
Next, it computes the coordinates of the overlapping rectangle as follows:

  • left boundary = max(ax1, bx1)
  • right boundary = min(ax2, bx2)
  • bottom boundary = max(ay1, by1)
  • top boundary = min(ay2, by2)

If the right boundary is greater than the left and the top boundary is greater than the bottom, the rectangles overlap and the overlapping area is computed as (right - left) * (top - bottom).
Finally, the total covered area is the sum of both rectangles’ areas minus the overlapping area (if any). The approach uses constant time calculations and does not require any extra data structures, leading to O(1) time and space complexities.


Code Solutions

# Calculate the total area covered by two rectangles
def rectangleArea(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2):
    # Calculate areas of individual rectangles
    area1 = (ax2 - ax1) * (ay2 - ay1)
    area2 = (bx2 - bx1) * (by2 - by1)
    
    # Find overlapping region boundaries
    overlap_left = max(ax1, bx1)
    overlap_right = min(ax2, bx2)
    overlap_bottom = max(ay1, by1)
    overlap_top = min(ay2, by2)
    
    # Calculate overlapping area if the rectangles overlap
    overlap_area = 0
    if overlap_right > overlap_left and overlap_top > overlap_bottom:
        overlap_area = (overlap_right - overlap_left) * (overlap_top - overlap_bottom)
    
    # Total area is sum of both areas minus overlapping area (if any)
    return area1 + area2 - overlap_area

# Example usage:
print(rectangleArea(-3, 0, 3, 4, 0, -1, 9, 2))
← Back to All Questions