Total area of overlapping rectangles
Posted: 10 Nov, 2020
You are given two arbitrary rectangles on a 2-D coordinate plane, which may have an intersecting area. You have to find the net area covered by both the rectangles on the cartesian plane.
The orange area depicted in the above figure is the net area covered by both rectangles on the cartesian plane.
1. For a rectangle, its top left and bottom right coordinates are given. 2. Coordinates of the rectangles are integer values. 3. Edges of the given rectangles will always be parallel to the X and Y coordinate axes of the cartesian plane. 4. It is guaranteed that both the rectangles will have at least a unit area.
The first line of the input contains an integer 'T' denoting the number of test cases. The first line of each test case contains 4 space-separated integer values 'x1', 'y1', 'x2', 'y2' denoting the top left ('x1', 'y1') and bottom-right ('x2', 'y2') coordinates of the first rectangle. The second line of each test case contains 4 space-separated integer values 'x3', 'y3', 'x4', 'y4' denoting the top left ('x3', 'y3') and bottom-right ('x4', 'y4') coordinates of the second rectangle.
For each test case, return an integer denoting the net area of two rectangles.
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10^5 -10^9 <= x1, y1, x2, y2 <= 10^9 x1 < x2, x3 < x4 y1 > y2, y3 > y4 Time Limit: 1sec
- The problem is essentially two questions:
- How to know if the two rectangles have an intersecting area? Because if they do have some common area we need to subtract it from our final answer.
- If the two rectangles have a common area, how to find it?
- Let’s consider two rectangles rectangle1 and rectangle2. Where left-most top point and right-most bottom point of rectangle1 are ('x1', ‘y1’), ('x2', ‘y2’). And the same for rectangle2 are ('x3', ‘y3’), ('x4', ‘y4’).
- To know if two rectangles have some common area, we need to consider only four situations: ‘x1’ >= ‘x4’ or ‘y1’ <= ‘y4’ or ‘x2’ <= ‘x3' or ‘y2’ >= ‘y3’. In such cases, rectangle ('x1', ‘y1’, ‘x2’, ‘y2’) will not overlap with the rectangle ('x3', ‘y3’, ‘x4’, ‘y4’).
- To calculate the common area, we only need to know the coordinates of the bottom left corner and top right corner of the overlapped area.
- In any case we only need to know max('x1', ‘x3’), min('x2', ‘x4’), max('y1', ‘y3’) and min('y2', ‘y4’) to calculate the overlapped area.
- Net area = Area of rectangle 1 + Area of rectangle 2 - Intersection or Overlapped area.
Animals And Monsters
Posted: 1 Oct, 2021
Save Ninja Land
Posted: 12 Nov, 2021
Construct The Parameter
Posted: 28 Nov, 2021
Posted: 13 Dec, 2021
Posted: 22 Apr, 2022