Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- The key idea is that XOR behaves like addition in binary, where XORing the same number twice cancels it out.
- 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.
- 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.
- 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.
- This lets us efficiently explore all subarrays without explicitly checking each one.
- """
- class Solution:
- def subarrayXor(self, arr, k):
- ans=0
- cur=0
- dict={0:1}
- for i in arr:
- cur=cur ^ i
- ans+= dict.get(cur^k,0)
- dict[cur]=dict.get(cur,0)+1
- return ans
Advertisement
Add Comment
Please, Sign In to add comment