Skip to content

Commit d308bca

Browse files
authored
Create count-triplets-with-even-xor-set-bits-ii.py
1 parent 6b9b19b commit d308bca

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# Time: O(nlogr), r = max(max(a), max(b), max(c))
2+
# Space: O(1)
3+
4+
# bit manipulation, parity
5+
class Solution(object):
6+
def tripletCount(self, a, b, c):
7+
"""
8+
:type a: List[int]
9+
:type b: List[int]
10+
:type c: List[int]
11+
:rtype: int
12+
"""
13+
def popcount(x):
14+
return bin(x).count('1')
15+
16+
def count(a):
17+
odd = sum(popcount(x)&1 for x in a)
18+
return [len(a)-odd, odd]
19+
20+
cnt = map(count, (a, b, c))
21+
return sum(cnt[0][0 if i == 0 or i == 1 else 1]*cnt[1][0 if i == 0 or i == 2 else 1]*cnt[2][0 if i == 0 or i == 3 else 1] for i in xrange(4))
22+
23+
24+
# Time: O(nlogr), r = max(max(a), max(b), max(c))
25+
# Space: O(1)
26+
# bit manipulation, parity
27+
class Solution2(object):
28+
def tripletCount(self, a, b, c):
29+
"""
30+
:type a: List[int]
31+
:type b: List[int]
32+
:type c: List[int]
33+
:rtype: int
34+
"""
35+
def popcount(x):
36+
return bin(x).count('1')
37+
38+
def count(a):
39+
odd = sum(popcount(x)&1 for x in a)
40+
return [len(a)-odd, odd]
41+
42+
even1, odd1 = count(a)
43+
even2, odd2 = count(b)
44+
even3, odd3 = count(c)
45+
return even1*even2*even3 + even1*odd2*odd3 + odd1*even2*odd3 + odd1*odd2*even3

0 commit comments

Comments
 (0)