#3382

Maximum Area Rectangle With Point Constraints II

Hard
ArrayMathBinary Indexed TreeSegment TreeGeometrySortingHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n²)Space O(n)

Sort points by x-coordinates and then by y-coordinates. Use a set to track points and check for valid rectangles efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort points by x-coordinates, then by y-coordinates.
  2. 2Step 2: Use a nested loop to select pairs of y-coordinates for each unique x-coordinate.
  3. 3Step 3: Check if the rectangle formed by these pairs has no other points inside or on the border using a set.
solution.py12 lines
1def maxArea(xCoord, yCoord):
2    points = sorted(zip(xCoord, yCoord))
3    point_set = set(points)
4    max_area = -1
5    for i in range(len(points)):
6        for j in range(i + 1, len(points)):
7            if points[i][0] != points[j][0]:
8                y1, y2 = points[i][1], points[j][1]
9                if not any((x, y1) in point_set or (x, y2) in point_set for x in range(points[i][0] + 1, points[j][0])):
10                    area = abs(points[i][0] - points[j][0]) * abs(y1 - y2)
11                    max_area = max(max_area, area)
12    return max_area

Complexity note: Sorting takes O(n log n) and checking pairs takes O(n²), but using a set allows for quick lookups.

  • 1Sorting helps in efficiently checking valid rectangles.
  • 2Using a set allows for O(1) lookups to check for points inside.

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