deepak_prakash's blog

By deepak_prakash, history, 7 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

»
7 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

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

    No, let's say subarray looks something like this: [a,b, c, d, e]. Xor of a and e should equal to b^c^d.

  • »
    »
    7 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.

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

Ig this problem came in one of CodeChef contest

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

Let's consider the prefix xor array $$$p[i]$$$, then the condition can be rewritten as $$$a[l] \oplus a[r] = p[l] \oplus p[r - 1]$$$. You can rewrite the condition again as $$$a[l] \oplus p[l] = a[r] \oplus p[r - 1]$$$ and then all you have to do is iterate from the suffix, maintain a counter $$$cnt$$$ for $$$a[r] \oplus p[r - 1]$$$ and add $$$cnt[a[i] \oplus p[i]]$$$ to the answer.

»
7 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)

»
7 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