Rectangle Area Problem
Description
LeetCode Problem 223.
Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.
The first rectangle is defined by its bottom-left corner (ax1, ay1) and its top-right corner (ax2, ay2).
The second rectangle is defined by its bottom-left corner (bx1, by1) and its top-right corner (bx2, by2).
Example 1:
Input: ax1 = -3, ay1 = 0, ax2 = 3, ay2 = 4, bx1 = 0, by1 = -1, bx2 = 9, by2 = 2
Output: 45
Example 2:
Input: ax1 = -2, ay1 = -2, ax2 = 2, ay2 = 2, bx1 = -2, by1 = -2, bx2 = 2, by2 = 2
Output: 16
Constraints:
- -10^4 <= ax1, ay1, ax2, ay2, bx1, by1, bx2, by2 <= 10^4
Solution
Approach: Inclusion-Exclusion
The area covered by both rectangles together is the sum of their areas minus the part they share, which would otherwise be counted twice.
The shared part, if there is one, is itself an axis-aligned rectangle:
- Its left edge is the larger of the two left edges,
max(ax1, bx1), and its right edge is the smaller of the two right edges,min(ax2, bx2). So its width ismin(ax2, bx2) - max(ax1, bx1). - Its height is
min(ay2, by2) - max(ay1, by1)in the same way.
If the rectangles do not meet in some direction, that difference is zero or negative. Clamp both the width and the height to at least 0 before multiplying. A common mistake is to multiply first: two negative sides would give a positive "overlap" for rectangles that are far apart.
The answer is areaA + areaB - overlapWidth * overlapHeight. With coordinates within ±104, each area is at most 4 × 108, so the sum fits in a 32-bit integer.
Complexity: O(1) time and O(1) space.
class Solution:
def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int,
bx1: int, by1: int, bx2: int, by2: int) -> int:
area_a = (ax2 - ax1) * (ay2 - ay1)
area_b = (bx2 - bx1) * (by2 - by1)
# The overlap is a rectangle too; its sides are negative when the rectangles do not meet.
overlap_width = min(ax2, bx2) - max(ax1, bx1)
overlap_height = min(ay2, by2) - max(ay1, by1)
overlap = max(overlap_width, 0) * max(overlap_height, 0)
return area_a + area_b - overlap
Now write it from memory
Close the write-up and solve it yourself against the tests.