[LeetCode] Minimum Area Rectangle

939. Minimum Area Rectangle

You are given an array of points in the X-Y plane points where points[i] = [xi, yi].

Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return 0.

  • Time : O(n^2)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
unordered_map<int, set<int>> pos;
public:
int minAreaRect(vector<vector<int>>& po) {
int res = INT_MAX;
for(auto& p : po) {
pos[p[0]].insert(p[1]);
}

for(int i = 0; i < po.size(); i++) {
for(int j = i + 1; j < po.size(); j++) {
if(po[i][0] == po[j][0] || po[i][1] == po[j][1]) continue;
int area = abs(po[j][0] - po[i][0]) * abs(po[j][1] - po[i][1]);
if(area >= res) continue;
if(pos[po[i][0]].count(po[j][1]) and pos[po[j][0]].count(po[i][1])) res = area;

}
}

return res == INT_MAX ? 0 : res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/17/PS/LeetCode/minimum-area-rectangle/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.