[AlgoExpert] Rectangle Mania

Rectangle Mania

  • 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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <vector>

using namespace std;

int intersection(vector<int>& A, vector<int>& B) {
int res = 0, i = 0, j = 0;
while(i < A.size() and j < B.size()) {
if(A[i] == B[j]) {
res++,i++,j++;
} else if(A[i] < B[j]) {
i++;
} else {
j++;
}
}
return res;
}

int rectangleMania(vector<vector<int>> coords) {
unordered_map<int, vector<int>> mp;
int res = 0;
for(auto& coord: coords) {
mp[coord[0]].push_back(coord[1]);
}
for(auto& [_, xaxis] : mp) {
sort(begin(xaxis), end(xaxis));
}
for(auto i = begin(mp); i != end(mp); i++) {
for(auto j = next(i); j != end(mp); j++) {
int intersectCount = intersection(i->second, j->second);
res += (intersectCount) * (intersectCount - 1) / 2;
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/09/PS/AlgoExpert/rectangle-mania/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.