imashutosh51

Count Subarrays with given XOR

Feb 5th, 2026
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.93 KB | None | 0 0
  1. """
  2. The key idea is that XOR behaves like addition in binary, where XORing the same number twice cancels it out.
  3. If we keep a running prefix XOR, the XOR of any subarray from index i to j can be found by XORing the prefix at j with the prefix at i-1.
  4. For example, for arr = [4, 2, 2, 6, 4] and k = 6, the prefix XORs are [4, 6, 4, 2, 6]; when we reach the last element (prefix XOR 6), we can see that prefix XOR 0 existed before, so subarray [4,2,2,6,4] has XOR 6.
  5. By storing counts of all prefix XORs seen so far, we can quickly check how many subarrays ending at the current element have XOR k.
  6. This lets us efficiently explore all subarrays without explicitly checking each one.
  7. """
  8. class Solution:
  9.     def subarrayXor(self, arr, k):
  10.         ans=0
  11.         cur=0
  12.         dict={0:1}
  13.         for i in arr:
  14.             cur=cur ^ i
  15.             ans+= dict.get(cur^k,0)
  16.             dict[cur]=dict.get(cur,0)+1
  17.    
  18.         return ans
Advertisement
Add Comment
Please, Sign In to add comment