
Sponsored
Sponsored
This approach involves calculating the area of each rectangle separately, then finding the overlapping area, and subtracting it from the total. First, calculate the area of each rectangle by using the formula width multiplied by height. To find the overlap, determine the maximum of the bottom-left x and y coordinates, and the minimum of the top-right x and y coordinates. If the rectangles do intersect, subtract the overlap area from the sum of the rectangle areas to get the total covered area.
The time complexity is O(1) since it involves basic arithmetic operations, and the space complexity is also O(1) as no additional space is needed beyond a few variables.
1def computeArea(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2):
2 area1 = (ax2 - ax1) * (ay2 - ay1)
3 area2 = (bx2 - bx1) * (by2 - by1)
4 overlapWidth = min(ax2, bx2) - max(ax1, bx1)
5 overlapHeight = min(ay2, by2) - max(ay1, by1)
6 overlapArea = 0
7 if overlapWidth > 0 and overlapHeight > 0:
8 overlapArea = overlapWidth * overlapHeight
9 return area1 + area2 - overlapArea
10
11print(computeArea(-3, 0, 3, 4, 0, -1, 9, 2))
12print(computeArea(-2, -2, 2, 2, -2, -2, 2, 2))
13This Python script computes the area covered by two rectangles. It does so by calculating the total of each rectangle's area, then finding and subtracting any overlapping area. This approach uses straightforward arithmetic operations to achieve the result.
By using the coordinate sweep method, we can iterate through all points in a uniform grid covering both rectangles. This technique conceptualizes sweeping lines across the plane, adding and subtracting areas as intersections are counted. Use sorting and a plane-sweep technique to determine overlapping intervals more effectively.
The time complexity remains O(1) since it involves constant time computation, while the space complexity is also O(1) because it uses a constant number of variables.
1
class Solution {
public bool IsOverlapping(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
return !(ax1 >= bx2 || bx1 >= ax2 || ay1 >= by2 || by1 >= ay2);
}
public int ComputeArea(int ax1, int ay1, int ax2, int ay2, int bx1, int by1, int bx2, int by2) {
int area1 = (ax2 - ax1) * (ay2 - ay1);
int area2 = (bx2 - bx1) * (by2 - by1);
int overlapArea = 0;
if (IsOverlapping(ax1, ay1, ax2, ay2, bx1, by1, bx2, by2)) {
int overlapWidth = Math.Min(ax2, bx2) - Math.Max(ax1, bx1);
int overlapHeight = Math.Min(ay2, by2) - Math.Max(ay1, by1);
overlapArea = overlapWidth * overlapHeight;
}
return area1 + area2 - overlapArea;
}
static void Main() {
Solution solution = new Solution();
Console.WriteLine(solution.ComputeArea(-3, 0, 3, 4, 0, -1, 9, 2));
Console.WriteLine(solution.ComputeArea(-2, -2, 2, 2, -2, -2, 2, 2));
}
}The C# solution determines whether two rectangles overlap and computes their combined area by subtracting any overlap. Simplified conditional logic determines if rectangles meet overlap criteria based on bounding conditions.