deepak_prakash's blog

By deepak_prakash, history, 13 months ago, In English

Hey, I recently got this problem in an online assessment.

Count number of subarrays such that, xor of first and last element of subarray should be equal to xor of remaining elements in the subarray. And the minimum size of subarray in consideration would be greater than equal to 3.

Thanks

  • Vote: I like it
  • +3
  • Vote: I do not like it

| Write comment?
»
13 months ago, # |
  Vote: I like it +28 Vote: I do not like it

xor of first and last element of subarray should be equal to xor of remaining elements in the subarray

this means the subarray's xor=0

  • »
    »
    13 months ago, # ^ |
      Vote: I like it +13 Vote: I do not like it

    Yes, now that I think the way I descibed, it means exactly what you're saying.

»
13 months ago, # |
  Vote: I like it +1 Vote: I do not like it

Ig this problem came in one of CodeChef contest

»
13 months ago, # |
  Vote: I like it +4 Vote: I do not like it

Here's an $$$O(N)$$$ solution:

We want to count subarrays such that:

$$$a[l] \oplus a[r] = a[l+1] \oplus \dots \oplus a[r-1]$$$

$$$0 = a[l] \oplus \dots \oplus a[r]$$$

$$$a[1] \oplus \dots \oplus a[l-1] = a[1] \oplus \dots a[r]$$$

Now, for a fixed $$$r$$$, we just need to count the number of $$$l$$$ such that the equation is true. We can do so in $$$O(1)$$$ via prefix sums stored in a hashmap.

Code:

from collections import defaultdict

n = int(input())
a = [None] + list(map(int, input().split()))

ans = 0

l_pxor = defaultdict(int)
pxor = [0] * (n+1)
for i in range(1, n+1):
    if i >= 3:
        # We can now consider subarray with l==i-2
        l_pxor[pxor[i-3]] += 1

    pxor[i] = a[i] ^ pxor[i-1]

    ans += l_pxor[pxor[i]]

print(ans)

»
13 months ago, # |
  Vote: I like it 0 Vote: I do not like it

I guess you can just count the number of subarrays with 0 xor, by using prefix_xor and some combinatorics