1620. XOR Pairs in a Band
A radio club assigns each of its n members a 16-bit handshake code, given as nums. Two members can pair up on a channel when the bitwise XOR of their codes lies inside a "quiet band". The band is the closed range between lo and hi; if lo is larger than hi, the two bounds are simply swapped first.
Count the unordered pairs of positions i < j whose XOR nums[i] ^ nums[j] falls inside the band. Equal codes at different positions are different members, so duplicates count separately. The answer can exceed 32 bits. Checking all pairs is too slow for large n; the intended solution runs in O(n log M) time with O(n log M) space, where M = 2^16.
Example 1
- Input:
- nums = [1,4,2,7], lo = 3, hi = 5
- Output:
- 4
- Explanation:
The six pair XORs are 5, 3, 6, 6, 3 and 5; the four that lie in [3, 5] are 5, 3, 3 and 5, so the answer is 4.
Example 2
- Input:
- nums = [4,4,4], lo = 1, hi = 9
- Output:
- 0
- Explanation:
All three pairs XOR to 0, which is below the band, so the answer is 0.
Constraints
1 ≤ nums.length ≤ 105
0 ≤ nums[i] < 216
0 ≤ lo, hi < 216 (if lo > hi they are swapped)
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 5,600 msC++ 1,400 msJava 2,800 msJavaScript 2,800 msTypeScript 2,800 ms
Expected complexity
- Time
- O(n log M)
- Space
- O(n log M)