3047. Find the Largest Area of Square Inside Two Rectangles

  • Array
  • Math
  • Geometry
TIME
O(n²)
SPACE
O(1)
problem on leetcode ↗source on github ↗

Intuition

For each pair of rectangles, compute their intersection. If the intersection exists, the largest square that fits inside it has a side length equal to the minimum of the intersection's width and height.

Solution

  1. Iterate all pairs: Check every pair of rectangles (i, j) where i < j.

  2. Compute intersection: For rectangles A and B:

    • left = max(A.x1, B.x1)
    • right = min(A.x2, B.x2)
    • bottom = max(A.y1, B.y1)
    • top = min(A.y2, B.y2)
  3. Check validity: Intersection exists if right > left and top > bottom.

  4. Compute max square side: If intersection exists, the largest square side is min(right - left, top - bottom).

  5. Track maximum: Keep the maximum side across all pairs.

  6. Return area: Return maxSide * maxSide.

Complexity

  • Time: O(n²), checking all pairs of rectangles
  • Space: O(1), only storing max side

Edge Cases

  • No rectangles intersect → return 0
  • Intersection is a line (width or height is 0) → no square fits
  • Multiple pairs have same max square → any valid answer works

Code

from typing import List


class Solution:
    def largestSquareArea(self, bottomLeft: List[List[int]], topRight: List[List[int]]) -> int:
        """
        3047. Find the Largest Area of Square Inside Two Rectangles
        Time: O(n²)
        Space: O(1)
        """
        n = len(bottomLeft)
        max_side = 0

        for i in range(n):
            ax1, ay1 = bottomLeft[i]
            ax2, ay2 = topRight[i]

            for j in range(i + 1, n):
                bx1, by1 = bottomLeft[j]
                bx2, by2 = topRight[j]

                left = max(ax1, bx1)
                right = min(ax2, bx2)
                bottom = max(ay1, by1)
                top = min(ay2, by2)

                if right > left and top > bottom:
                    side = min(right - left, top - bottom)
                    max_side = max(max_side, side)

        return max_side * max_side