Блог пользователя deepak_prakash

Автор deepak_prakash, история, 7 месяцев назад, По-английски

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

  • Проголосовать: нравится
  • +3
  • Проголосовать: не нравится

»
7 месяцев назад, # |
  Проголосовать: нравится +28 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится +1 Проголосовать: не нравится

Ig this problem came in one of CodeChef contest

»
7 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится +4 Проголосовать: не нравится

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 месяцев назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

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