Problem
There exist n
rectangles in a 2D plane with edges parallel to the x and y axis. You are given two 2D integer arrays bottomLeft
and topRight
where
bottomLeft[i] = [a_i, b_i]
and topRight[i] = [c_i, d_i]
represent the
bottom-left and top-right coordinates of the ith
rectangle, respectively.
You need to find the maximum area of a square that can fit inside the intersecting region of at least two rectangles. Return 0
if such a square does not exist.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
n == bottomLeft.length == topRight.length
2 <= n <= 10^3
bottomLeft[i].length == topRight[i].length == 2
1 <= bottomLeft[i][0], bottomLeft[i][1] <= 10^7
1 <= topRight[i][0], topRight[i][1] <= 10^7
bottomLeft[i][0] < topRight[i][0]
bottomLeft[i][1] < topRight[i][1]
Solution
Method 1 – Pairwise Rectangle Intersection + Greedy Square Fitting
Intuition
The largest square that can fit inside the intersection of two rectangles is determined by the width and height of their overlapping region. For each pair of rectangles, compute their intersection, and check the largest square that fits. The answer is the maximum such square area among all pairs.
Approach
- For every pair of rectangles:
- Compute the intersection region (if any) by taking the max of bottom-lefts and min of top-rights.
- If the intersection is valid (width > 0 and height > 0), the largest square that fits has side = min(width, height).
- Track the maximum square area found among all pairs.
- Return 0 if no intersection exists for any pair.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n^2)
, as we check all pairs of rectangles. - 🧺 Space complexity:
O(1)
, only a few variables are used for computation.