Minimum Area Rectangle

Axis-aligned rectangles — group points by x, for every pair of x-columns find shared y-pairs and compute area.

Medium
Time O(n^2) average Space O(n)
LeetCode
6 min read
geometry hash-set math

Problem#

Given a set of 2D points, find the minimum area of any axis-aligned rectangle whose four corners are in the set, or 0 if none exists.

Examples#

  • [[1,1],[1,3],[3,1],[3,3],[2,2]]4.
  • [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]2.

Constraints#

  • 1 <= points.length <= 500, coordinates in [0, 4*10^4].

Approach#

Bucket points by x: cols[x] = sorted ys. For each pair of x-columns, two-pointer / set-intersect their y-lists. Each pair of shared ys forms a rectangle of width |x1 - x2| and height y2 - y1.

Solution#

Minimum Area Rectangle
class Solution {
public:
int minAreaRect(vector<vector<int>>& points) {
map<int, vector<int>> cols;
for (auto& p : points) cols[p[0]].push_back(p[1]);
for (auto& [_, ys] : cols) sort(ys.begin(), ys.end());
int ans = INT_MAX;
vector<pair<int, vector<int>*>> arr;
for (auto& [x, ys] : cols) arr.push_back({x, &ys});
for (int i = 0; i < (int)arr.size(); ++i)
for (int j = i + 1; j < (int)arr.size(); ++j) {
auto& A = *arr[i].second;
auto& B = *arr[j].second;
int dx = arr[j].first - arr[i].first;
int a = 0, b = 0, prev = -1;
while (a < (int)A.size() && b < (int)B.size()) {
if (A[a] == B[b]) {
if (prev != -1) ans = min(ans, dx * (A[a] - prev));
prev = A[a];
++a; ++b;
} else if (A[a] < B[b]) ++a;
else ++b;
}
}
return ans == INT_MAX ? 0 : ans;
}
};

Editorial#

Restricting to axis-aligned rectangles lets us decompose: two distinct x-columns plus two shared ys. Two-pointer-intersecting the ys keeps the inner loop linear, and tracking only consecutive shared ys is enough because non-adjacent pairs give larger heights.

Complexity#

  • Time: O(n^2) average; worst case dominated by intersections.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.