Count Pairs With XOR in a Range LeetCode solution in Python

1
class Solution:
2
def countPairs(self, nums, low, high):
3
return self._countPairs(nums, high + 1) - self._countPairs(nums, low)
4

5
def _countPairs(self, nums, high):
6
res = 0
7
for k in range(31, -1, -1):
8
target = high >> k
9
if target & 1 == 0:
10
continue
11
target -= 1
12
counter = Counter(num >> k for num in nums)
13
for mask in counter:
14
res += counter[mask] * counter[target ^ mask]
15
if mask == target ^ mask:
16
res -= counter[mask]
17
return res // 2

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0