Given the coordinates of two rectilinear rectangles in a 2D plane, return the total area covered by the two rectangles.
Each rectangle is defined by its bottom-left corner and top-right corner as (A, B)
and (C, D)
for the first rectangle, and (E, F)
and (G, H)
for the second rectangle.
class Solution {
public:
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
// Calculate the area of both the rectangles separately
int area1 = (C - A) * (D - B);
int area2 = (G - E) * (H - F);
// Calculate the overlapping area
int overlapWidth = max(0, min(C, G) - max(A, E));
int overlapHeight = max(0, min(D, H) - max(B, F));
int overlapArea = overlapWidth * overlapHeight;
// Total area covered by both rectangles
int totalArea = area1 + area2 - overlapArea;
return totalArea;
}
};
The time complexity of this solution is ( O(1) ) because it involves a fixed number of arithmetic operations and comparisons regardless of the actual input values.
For the rectangles defined by (A, B, C, D)
as (0, 0, 2, 2) and (E, F, G, H)
as (1, 1, 3, 3):
This approach ensures accurate calculation of the total area covered by the two rectangles, accounting correctly for any overlaps.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?