Skip to content

Commit 7f0bfef

Browse files
authored
Update count-equal-and-divisible-pairs-in-an-array.cpp
1 parent a8a2cde commit 7f0bfef

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

C++/count-equal-and-divisible-pairs-in-an-array.cpp

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Time: O(n * sqrt(k))
2-
// Space: O(n + sqrt(k))
2+
// Space: O(n + sqrt(k)), number of factors of k is at most sqrt(k)
33

44
// math, number theory
55
class Solution {
@@ -26,10 +26,35 @@ class Solution {
2626
}
2727
};
2828

29+
// Time: O(nlogk + n * sqrt(k)^2) = O(n * k)
30+
// Space: O(n * sqrt(k)), number of factors of k is at most sqrt(k)
31+
// math, number theory
32+
class Solution2 {
33+
public:
34+
int countPairs(vector<int>& nums, int k) {
35+
unordered_map<int, unordered_map<int, int>> cnts;
36+
for (int i = 0; i < size(nums); ++i) {
37+
++cnts[nums[i]][gcd(i, k)];
38+
}
39+
int result = 0;
40+
for (const auto& [_, cnt] : cnts) {
41+
for (const auto& [x, c1] : cnt) {
42+
for (const auto& [y, c2] : cnt) {
43+
if (x > y || x * y % k) {
44+
continue;
45+
}
46+
result += (x != y) ? c1 * c2 : c1 * (c1 - 1) / 2;
47+
}
48+
}
49+
}
50+
return result;
51+
}
52+
};
53+
2954
// Time: O(n^2)
3055
// Space: O(n)
3156
// brute force
32-
class Solution2 {
57+
class Solution3 {
3358
public:
3459
int countPairs(vector<int>& nums, int k) {
3560
unordered_map<int, vector<int>> idxs;

0 commit comments

Comments
 (0)