#3047

Find the Largest Area of Square Inside Two Rectangles

Medium
ArrayMathGeometryGeometrySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach leverages the fact that we only need to consider the edges of rectangles to determine potential square sizes. By focusing on the coordinates of the rectangles, we can efficiently find the maximum square area without checking every pair.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a list of all unique x-coordinates and y-coordinates from the rectangles.
  2. 2Step 2: Sort these coordinates and iterate through them to find potential square sizes.
  3. 3Step 3: For each pair of adjacent coordinates, calculate the potential square side length and check if it can fit in the overlapping area of rectangles.
  4. 4Step 4: Keep track of the maximum area found.
solution.py10 lines
1def maxSquareArea(bottomLeft, topRight):
2    x_coords = sorted(set(x for rect in bottomLeft + topRight for x in rect))
3    y_coords = sorted(set(y for rect in bottomLeft + topRight for y in rect))
4    max_area = 0
5    for i in range(len(x_coords) - 1):
6        for j in range(len(y_coords) - 1):
7            side_length = min(x_coords[i + 1] - x_coords[i], y_coords[j + 1] - y_coords[j])
8            if side_length > 0:
9                max_area = max(max_area, side_length * side_length)
10    return max_area

Complexity note: The time complexity is O(n log n) due to sorting the unique coordinates, while the space complexity is O(n) for storing these coordinates.

  • 1Understanding rectangle intersection is crucial for solving this problem.
  • 2The size of the square is limited by the smallest dimension of the intersection area.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.