Subarrays with XOR at Least K Problem
Description
LeetCode Problem 3632.
Given an array of positive integers nums of length n and a non‑negative integer k.
Return the number of contiguous subarrays whose bitwise XOR of all elements is greater than or equal to k.
Example 1:
Input: nums = [3,1,2,3], k = 2
Output: 6
Explanation:
The valid subarrays with XOR >= 2 are [3] at index 0, [3, 1] at indices 0 - 1, [3, 1, 2, 3] at indices 0 - 3, [1, 2] at indices 1 - 2, [2] at index 2, and [3] at index 3; there are 6 in total.
Example 2:
Input: nums = [0,0,0], k = 0
Output: 6
Explanation:
Every contiguous subarray yields XOR = 0, which meets k = 0. There are 6 such subarrays in total.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^90 <= k <= 10^9
Solution
Approach: Prefix XOR + Grouping by Bit Prefixes
Let pre[i] be the XOR of the first i elements. The XOR of a subarray is pre[i] ^ pre[j], so we need the number of pairs of prefix values (there are n + 1 of them) whose XOR is at least k.
Compare x = pre[i] ^ pre[j] with k from the highest bit down. x >= k holds exactly when x == k, or there is a bit b where k has 0 and x has 1 while all higher bits of x and k agree. For each such bit b this means (pre[i] >> b) ^ (pre[j] >> b) == (k >> b) | 1. So for every candidate b (and once for x == k) we count the pairs whose shifted values XOR to a given target t, using a hash map of counts: each value u pairs with u ^ t, and each pair is seen twice. When t = 0 the pairs are two equal values.
The cases are disjoint, so the counts add up to the answer.
Complexity: O(n log M) time and O(n) space, where n is the length of the array and M the maximum value.
from collections import Counter
class Solution:
def countXorSubarrays(self, nums: List[int], k: int) -> int:
pre = [0]
for x in nums:
pre.append(pre[-1] ^ x)
def pairs(shift: int, t: int) -> int:
# number of pairs (i < j) with (pre[i] >> shift) ^ (pre[j] >> shift) == t
cnt = Counter(p >> shift for p in pre)
if t == 0:
return sum(c * (c - 1) // 2 for c in cnt.values())
return sum(c * cnt.get(u ^ t, 0) for u, c in cnt.items()) // 2
ans = pairs(0, k)
for b in range(30):
if (k >> b) & 1 == 0:
ans += pairs(b, (k >> b) | 1)
return ans