![]() |
VOOZH | about |
Given coordinates of 4 points, bottom-left and top-right corners of two rectangles. The task is to find the coordinates of the intersecting rectangle formed by the given two rectangles.
Examples:
Input:
rec1: bottom-left(0, 0), top-right(10, 8),
rec2: bottom-left(2, 3), top-right(7, 9)
Output: (2, 3) (7, 8) (2, 8) (7, 3)
Input:
rec1: bottom-left(0, 0), top-right(3, 3),
rec2: bottom-left(1, 1), top-right(2, 2)
Output: (1, 1) (2, 2) (1, 2) (2, 1)
Approach :
As two given points are diagonals of a rectangle. so, x1 < x2, y1 < y2. similarly x3 < x4, y3 < y4.
so, bottom-left and top-right points of intersection rectangle can be found by using formula.
x5 = max(x1, x3); y5 = max(y1, y3); x6 = min(x2, x4); y6 = min(y2, y4);
In case of no intersection, x5 and y5 will always exceed x6 and y5 respectively. The other two points of the rectangle can be found by using simple geometry.
Below is the implementation of the above approach:
(2, 3) (7, 8) (2, 8) (7, 3)
Time Complexity: O(1)
Auxiliary Space: O(1)