Skip to content

Commit 6b9b19b

Browse files
authored
Create count-triplets-with-even-xor-set-bits-ii.cpp
1 parent 70e8f5b commit 6b9b19b

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// Time: O(nlogr), r = max(max(a), max(b), max(c))
2+
// Space: O(1)
3+
4+
// bit manipulation, parity
5+
class Solution {
6+
public:
7+
long long tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) {
8+
const auto& count = [](const auto& a) {
9+
const auto& odd = accumulate(cbegin(a), cend(a), 0, [](const auto& total, const auto& x) {
10+
return total + (__builtin_popcount(x) & 1);
11+
});
12+
return vector<int64_t>{static_cast<int>(size(a)) - odd, odd};
13+
};
14+
15+
vector<vector<int64_t>> cnt = {count(a), count(b), count(c)};
16+
int64_t result = 0;
17+
for (int i = 0; i < 4; ++i) {
18+
result += cnt[0][i == 0 || i == 1 ? 0 : 1] *
19+
cnt[1][i == 0 || i == 2 ? 0 : 1] *
20+
cnt[2][i == 0 || i == 3 ? 0 : 1];
21+
}
22+
return result;
23+
}
24+
};
25+
26+
// Time: O(nlogr), r = max(max(a), max(b), max(c))
27+
// Space: O(1)
28+
// bit manipulation, parity
29+
class Solution2 {
30+
public:
31+
long long tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) {
32+
const auto& count = [](const auto& a) {
33+
const auto& odd = accumulate(cbegin(a), cend(a), 0, [](const auto& total, const auto& x) {
34+
return total + (__builtin_popcount(x) & 1);
35+
});
36+
return pair<int64_t, int64_t>(static_cast<int>(size(a)) - odd, odd);
37+
};
38+
39+
const auto& [even1, odd1] = count(a);
40+
const auto& [even2, odd2] = count(b);
41+
const auto& [even3, odd3] = count(c);
42+
return even1 * even2 * even3 + even1 * odd2 * odd3 + odd1 * even2 * odd3 + odd1 * odd2 * even3;
43+
}
44+
};

0 commit comments

Comments
 (0)