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 and top-right coordinates as follows:
(A, B)
is the bottom-left corner and (C, D)
is the top-right corner.(E, F)
is the bottom-left corner and (G, H)
is the top-right corner.Are the coordinates always integers? Yes, the coordinates are given as integers.
Can the rectangles overlap? Yes, the rectangles can overlap.
What should be returned if there is no overlap? The sum of the areas of both rectangles should be returned if there is no overlap.
Can the rectangles be degenerate (i.e., form lines or points)? Yes, but they will not contribute any positive area in such cases.
We need to follow these steps to solve the problem:
(C - A) * (D - B)
(G - E) * (H - F)
max(0, min(C, G) - max(A, E))
max(0, min(D, H) - max(B, F))
public class RectangleArea {
public int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
// Calculate the area of the first rectangle
int area1 = (C - A) * (D - B);
// Calculate the area of the second rectangle
int area2 = (G - E) * (H - F);
// Calculate the overlapping area
int overlapWidth = Math.max(0, Math.min(C, G) - Math.max(A, E));
int overlapHeight = Math.max(0, Math.min(D, H) - Math.max(B, F));
int overlapArea = overlapWidth * overlapHeight;
// Total area is the sum of the individual areas minus the overlapping part
return area1 + area2 - overlapArea;
}
}
The time complexity of this solution is O(1) because all operations involved (min, max, and arithmetic) are performed in constant time.
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?