Data Structures & AlgorithmsHardProduct Company SDE · hashing round

Problem: Count subarrays whose XOR is zero, for a = [1, 2, 3, 0, 3, 3].

Problem: Count subarrays whose XOR is zero, for a = [1, 2, 3, 0, 3, 3].
from collections import Counter
def cnt(a):
    seen = Counter({0: 1})
    cur = 0
    ans = 0
    for x in a:
        cur ^= x
        ans += seen[cur]
        seen[cur] += 1
    return ans
print(cnt([1, 2, 3, 0, 3, 3]))
What is printed?
  1. A. 4
  2. B. 7
  3. C. 6
  4. D. 3

Correct answer: B. 7

Equal prefix XOR values bound a zero-XOR subarray. Prefix values 0, 1, 3, 0, 0, 3, 0 give C(4,2) + C(2,2) = 6 + 1 = 7 pairs. Omitting the initial {0: 1} gives 4, skipping the single-element subarray [0] gives 6, and counting only subarrays that start at index 0 gives 3.

More Coding Interview Problems questions

Exams that ask this topic