Maximum Area Rectangle With Point Constraints I

Find the largest axis-aligned rectangle whose four corners are in the point set and whose interior + boundary contain no other points.

Medium
Time O(n^4) brute Space O(n)
10 min read
geometry hash-set math

Problem#

Given a list of 2D points, find the largest axis-aligned rectangle whose four corners are points and whose interior plus boundary contains no other points. Return the area, or -1 if none exists. This is an curriculum variant — there is no LeetCode link.

Examples#

  • [[1,1],[1,3],[3,1],[3,3]]4.
  • [[1,1],[1,3],[3,1],[3,3],[2,2]]-1 (inner point spoils it).

Constraints#

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

Approach#

Group points by x. For each pair (x1, x2) of x-columns, two-pointer-intersect their y-lists. For each rectangle candidate (x1, x2, y1, y2), validate that no other point lies in [x1, x2] x [y1, y2] by scanning intermediate x-columns for ys in [y1, y2].

Solution#

Maximum Area Rectangle With Point Constraints I
class Solution {
public:
long long largestRectangleI(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());
vector<pair<int, vector<int>*>> arr;
for (auto& [x, ys] : cols) arr.push_back({x, &ys});
long long best = -1;
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;
vector<int> shared;
int a = 0, b = 0;
while (a < (int)A.size() && b < (int)B.size()) {
if (A[a] == B[b]) { shared.push_back(A[a]); ++a; ++b; }
else if (A[a] < B[b]) ++a; else ++b;
}
for (int p = 0; p + 1 < (int)shared.size(); ++p) {
int y1 = shared[p], y2 = shared[p + 1];
bool ok = true;
for (int m = i + 1; m < j && ok; ++m) {
auto& Y = *arr[m].second;
auto it = lower_bound(Y.begin(), Y.end(), y1);
if (it != Y.end() && *it <= y2) ok = false;
}
auto check = [&](vector<int>& Y, int y1, int y2) {
auto it = upper_bound(Y.begin(), Y.end(), y1);
return it != Y.end() && *it < y2;
};
if (ok && !check(A, y1, y2) && !check(B, y1, y2)) {
long long dx = arr[j].first - arr[i].first;
best = max(best, dx * (long long)(y2 - y1));
}
}
}
return best;
}
};

Editorial#

The validity check ensures no other point sits strictly inside or on the rectangle’s boundary (besides the four corners). Iterating only adjacent shared ys gives the smallest valid height per x-pair; we still pick the largest area across all pairs.

Complexity#

  • Time: O(n^2 log n) with sorted ys; brute is O(n^4).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.