LinkedIn – Interview – Find colinear points in O(n^2) | Yaozong's Blog
Strictly speaking, the following code is not O(n^2), because insert points into map takes O(logn). However, if we define hash functions for pair, it could be reduced to O(n^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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
vector<vector<pair<int,int>>> find_colinear_points(vector<pair<int,int>>& pts)
{
vector<vector<pair<int,int>>> res;
map<pair<double, double>, set<pair<int,int>>> ht;
map<double, set<pair<int,int>>> vert;
for (int i = 0; i < pts.size(); ++i)
{
for (int j = i + 1; j < pts.size(); ++j)
{
if (pts[i].first == pts[j].first) {
vert[pts[i].first].insert(pts[i]);
vert[pts[i].first].insert(pts[j]);
}
else {
int dx = pts[i].first - pts[j].first;
int dy = pts[i].second - pts[j].second;
double s = dy * 1.0 / dx;
double d = pts[i].second - s * pts[i].first;
ht[make_pair(s, d)].insert(pts[i]);
ht[make_pair(s, d)].insert(pts[j]);
}
}
}
for (auto elem : vert) {
if (elem.second.size() > 2) {
vector<pair<int, int>> tmp(elem.second.begin(), elem.second.end());
res.push_back(tmp);
}
}
for (auto elem : ht) {
if (elem.second.size() > 2) {
vector<pair<int, int>> tmp(elem.second.begin(), elem.second.end());
res.push_back(tmp);
}
}
return res;
}
Read full article from LinkedIn – Interview – Find colinear points in O(n^2) | Yaozong's Blog
Strictly speaking, the following code is not O(n^2), because insert points into map takes O(logn). However, if we define hash functions for pair, it could be reduced to O(n^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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
vector<vector<pair<int,int>>> find_colinear_points(vector<pair<int,int>>& pts)
{
vector<vector<pair<int,int>>> res;
map<pair<double, double>, set<pair<int,int>>> ht;
map<double, set<pair<int,int>>> vert;
for (int i = 0; i < pts.size(); ++i)
{
for (int j = i + 1; j < pts.size(); ++j)
{
if (pts[i].first == pts[j].first) {
vert[pts[i].first].insert(pts[i]);
vert[pts[i].first].insert(pts[j]);
}
else {
int dx = pts[i].first - pts[j].first;
int dy = pts[i].second - pts[j].second;
double s = dy * 1.0 / dx;
double d = pts[i].second - s * pts[i].first;
ht[make_pair(s, d)].insert(pts[i]);
ht[make_pair(s, d)].insert(pts[j]);
}
}
}
for (auto elem : vert) {
if (elem.second.size() > 2) {
vector<pair<int, int>> tmp(elem.second.begin(), elem.second.end());
res.push_back(tmp);
}
}
for (auto elem : ht) {
if (elem.second.size() > 2) {
vector<pair<int, int>> tmp(elem.second.begin(), elem.second.end());
res.push_back(tmp);
}
}
return res;
}
Read full article from LinkedIn – Interview – Find colinear points in O(n^2) | Yaozong's Blog