#223

Rectangle Area

Medium
MathGeometryGeometryMathematical Calculations
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(1)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution calculates the area of each rectangle and the overlapping area in constant time. This avoids any unnecessary iterations or complex calculations, leading to a more efficient solution.

⚙️

Algorithm

5 steps
  1. 1Step 1: Calculate the area of the first rectangle.
  2. 2Step 2: Calculate the area of the second rectangle.
  3. 3Step 3: Calculate the overlap width and height using the maximum and minimum functions.
  4. 4Step 4: Compute the overlapping area.
  5. 5Step 5: Return the total area minus the overlapping area.
solution.py12 lines
1# Full working Python code
2
3def compute_area(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2):
4    area1 = (ax2 - ax1) * (ay2 - ay1)
5    area2 = (bx2 - bx1) * (by2 - by1)
6    overlap_width = max(0, min(ax2, bx2) - max(ax1, bx1))
7    overlap_height = max(0, min(ay2, by2) - max(ay1, by1))
8    overlap_area = overlap_width * overlap_height
9    return area1 + area2 - overlap_area
10
11# Example usage
12print(compute_area(-2, -2, 2, 2, -2, -2, 2, 2))

Complexity note: The optimal solution also runs in constant time because it performs a fixed number of calculations, independent of the input size.

  • 1Understanding how to calculate the area of rectangles
  • 2Recognizing the importance of handling overlaps correctly

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.