#939

Minimum Area Rectangle

Medium
ArrayHash TableMathGeometrySortingHash 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)

Using a HashSet allows us to quickly check for the existence of the required rectangle corners, reducing unnecessary checks and improving efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: Store all points in a HashSet for O(1) lookup time.
  2. 2Step 2: Iterate through each pair of points to identify potential rectangle corners.
  3. 3Step 3: For each pair, check if the other two corners exist in the HashSet.
  4. 4Step 4: Calculate the area if all four corners are found and update the minimum area.
solution.py12 lines
1# Full working Python code
2from itertools import combinations
3
4def minAreaRect(points):
5    point_set = set(map(tuple, points))
6    min_area = float('inf')
7    for (x1, y1), (x2, y2) in combinations(points, 2):
8        if x1 != x2 and y1 != y2:
9            if (x1, y2) in point_set and (x2, y1) in point_set:
10                area = abs(x1 - x2) * abs(y1 - y2)
11                min_area = min(min_area, area)
12    return min_area if min_area != float('inf') else 0

Complexity note: The time complexity remains O(n²) because we still check every pair of points. However, the space complexity is O(n) due to the HashSet storing the points for quick lookup.

  • 1A rectangle requires opposite corners to be present.
  • 2Using a HashSet allows for faster existence checks.

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