#963
Minimum Area Rectangle II
MediumArrayHash TableMathGeometryHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n²)Space O(n)
We can use a HashMap to store points for quick lookup, and then iterate through pairs of points to determine if they can form a rectangle. This reduces the number of checks significantly.
⚙️
Algorithm
4 steps- 1Step 1: Store all points in a HashSet for O(1) lookup.
- 2Step 2: Iterate through each pair of points to consider them as potential opposite corners of a rectangle.
- 3Step 3: Calculate the potential other two corners and check if they exist in the HashSet.
- 4Step 4: If they exist, calculate the area and update the minimum area found.
solution.py14 lines
1def minAreaRect(points):
2 point_set = set(tuple(point) for point in points)
3 min_area = float('inf')
4 for i in range(len(points)):
5 for j in range(i + 1, len(points)):
6 p1, p2 = points[i], points[j]
7 # Calculate potential other corners
8 p3 = (p1[0], p2[1])
9 p4 = (p2[0], p1[1])
10 if p3 in point_set and p4 in point_set:
11 area = abs(p1[0] - p2[0]) * abs(p1[1] - p2[1])
12 min_area = min(min_area, area)
13 return min_area if min_area != float('inf') else 0
14ℹ
Complexity note: The time complexity remains O(n²) due to the nested loops, but we gain efficiency through O(1) lookups in the HashSet, making it faster in practice.
- 1The rectangle can be formed by any four points, not just those aligned with axes.
- 2Using a HashSet allows for quick lookups to verify potential rectangle corners.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.