Find the Largest Area of Square Inside Two Rectangles - 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] represents the bottom-left coordinates of the i-th rectangle

topRight[i] = [c_i, d_i] represents the top-right coordinates of the i-th rectangle

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.

Input & Output

Example 1 — Basic Intersection
$ Input: bottomLeft = [[1,1],[2,2],[3,1]], topRight = [[3,3],[4,4],[4,4]]
Output: 1
💡 Note: Rectangle 0: (1,1) to (3,3), Rectangle 1: (2,2) to (4,4). Their intersection is (2,2) to (3,3) with width=1, height=1. Largest square has side=1, area=1.
Example 2 — Larger Intersection
$ Input: bottomLeft = [[1,1],[2,2],[1,2]], topRight = [[4,4],[4,4],[3,4]]
Output: 4
💡 Note: Rectangle 0: (1,1) to (4,4), Rectangle 1: (2,2) to (4,4). Intersection is (2,2) to (4,4) with width=2, height=2. Largest square has side=2, area=4.
Example 3 — No Intersection
$ Input: bottomLeft = [[1,1],[3,3]], topRight = [[2,2],[4,4]]
Output: 0
💡 Note: Rectangle 0: (1,1) to (2,2), Rectangle 1: (3,3) to (4,4). These rectangles don't intersect, so no square can fit in a shared region.

Constraints

  • 2 ≤ n ≤ 5 × 104
  • bottomLeft[i].length == topRight[i].length == 2
  • -109 ≤ bottomLeft[i][j], topRight[i][j] ≤ 109
  • bottomLeft[i][0] < topRight[i][0] and bottomLeft[i][1] < topRight[i][1]

Visualization

Tap to expand
Find Largest Square in Rectangle IntersectionsInput: Multiple RectanglesRect 1Rect 2Rect 3Step 2: Find IntersectionsIntersectionStep 3: Largest SquareMax SquareAlgorithm: For intersection with width W, height H→ Largest square side = min(W, H)→ Square area = side²Return: Maximum area among all intersectionsTime Complexity: O(n²) | Space Complexity: O(1)
Understanding the Visualization
1
Input Rectangles
Given n rectangles with bottom-left and top-right coordinates
2
Find Intersections
Check all pairs of rectangles to find their overlapping regions
3
Calculate Largest Square
For each intersection, largest square side = min(width, height)
Key Takeaway
🎯 Key Insight: The largest square in any rectangular intersection has side length equal to the minimum dimension of that intersection
Asked in
Google 45 Amazon 32 Microsoft 28
28.4K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen