Problem Description
Given n rectangles in a 2D plane (with edges parallel to the axes), each defined by its bottom-left and top-right coordinates, find the maximum area of a square that can completely fit inside the intersection region of at least two rectangles. If no two rectangles intersect (or no square can fit in any intersection), return 0.
Key Insights
- The intersection of two rectangles (if it exists) is itself a rectangle with:
- bottom-left coordinates: (max(a₁, a₂), max(b₁, b₂))
- top-right coordinates: (min(c₁, c₂), min(d₁, d₂))
- The valid intersection exists only if min(c₁, c₂) > max(a₁, a₂) and min(d₁, d₂) > max(b₁, b₂).
- The side length of the largest square that can fit inside the intersected rectangle is the minimum of its width and height.
- A brute-force solution checking all pairs of rectangles will run in O(n²) time, which is acceptable given n ≤ 10³.
Space and Time Complexity
Time Complexity: O(n²) – We check every pair of rectangles. Space Complexity: O(1) – Only a few extra variables are used, aside from the input.
Solution
The approach is to iterate over each unique pair of rectangles and:
- Compute the intersection rectangle by taking the maximum of the bottom-left coordinates and the minimum of the top-right coordinates.
- If an intersection exists (i.e., the computed width and height are positive), determine the side length of the square that can fit by taking the minimum of the width and height.
- Update the maximum square area encountered.
- Return the result (maximum area, which is side²) or 0 if no valid intersection exists.
The solution uses straightforward arithmetic operations and simple comparisons. No complex data structures are needed.