#3380

Maximum Area Rectangle With Point Constraints I

Medium
ArrayMathBinary Indexed TreeSegment TreeGeometrySortingEnumerationHash 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)

By fixing two points as opposite corners of a rectangle, we can efficiently find the other two corners and check for point constraints using a set for quick lookups.

⚙️

Algorithm

6 steps
  1. 1Step 1: Store all points in a set for O(1) lookups.
  2. 2Step 2: Iterate through all pairs of points to consider them as opposite corners of a rectangle.
  3. 3Step 3: Calculate the other two corners based on the current pair.
  4. 4Step 4: Check if these two corners exist in the set.
  5. 5Step 5: Check if any point lies inside or on the border of the rectangle using the set.
  6. 6Step 6: Calculate the area if valid and update the maximum area found.
solution.py14 lines
1def maxArea(points):
2    point_set = set(map(tuple, points))
3    max_area = -1
4    n = len(points)
5    for i in range(n):
6        for j in range(i + 1, n):
7            x1, y1 = points[i]
8            x2, y2 = points[j]
9            if x1 != x2 and y1 != y2:
10                if (x1, y2) in point_set and (x2, y1) in point_set:
11                    area = abs(x1 - x2) * abs(y1 - y2)
12                    if all(not (min(x1, x2) <= px <= max(x1, x2) and min(y1, y2) <= py <= max(y1, y2)) for px, py in points if (px, py) not in {(x1, y1), (x2, y2)}):
13                        max_area = max(max_area, area)
14    return max_area

Complexity note: The time complexity remains O(n²) due to the nested loops, but we use O(n) space for the set to allow for quick point existence checks.

  • 1Using a set allows for quick checks of point existence.
  • 2Fixing two points reduces the complexity of finding the other corners.

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