223. Rectangle Area
- Math
- Geometry
TIME
O(1)
SPACE
O(1)
Intuition
Total area covered = Area of rectangle A + Area of rectangle B - Overlapping area (to avoid double counting).
Solution
Calculate individual areas: Compute area of each rectangle using
width × height.Find intersection bounds:
left = max(ax1, bx1)right = min(ax2, bx2)bottom = max(ay1, by1)top = min(ay2, by2)
Calculate intersection area:
- If
right > leftandtop > bottom, intersection exists - Intersection area =
(right - left) × (top - bottom) - Otherwise, intersection area = 0
- If
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/**
* 223. Rectangle Area
* Time: O(1)
* Space: O(1)
*/
class Solution {
public int computeArea(int ax1, int ay1, int ax2, int ay2,
int bx1, int by1, int bx2, int by2) {
int totalArea = ((ax2 - ax1) * (ay2 - ay1)) + ((bx2 - bx1) * (by2 - by1));
int intersectedLeft = Math.max(ax1, bx1);
int intersectedRight = Math.min(ax2, bx2);
int intersectedHorizontal = intersectedRight > intersectedLeft ? intersectedRight - intersectedLeft : 0;
int intersectedBottom = Math.max(ay1, by1);
int intersectedTop = Math.min(ay2, by2);
int intersectedVertical = intersectedTop > intersectedBottom ? intersectedTop - intersectedBottom : 0;
int intersectedArea = intersectedHorizontal * intersectedVertical;
return totalArea - intersectedArea;
}
}