Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Count triples (i, j, k) with i < j ≤ k such that XOR(a[i..j−1]) == XOR(a[j..k]). This holds iff XOR(a[i..k]) = 0, i.e. prefix[i] == prefix[k+1]; then every j in (i, k] works.

Problem: Count triples (i, j, k) with i < j ≤ k such that XOR(a[i..j−1]) == XOR(a[j..k]). This holds iff XOR(a[i..k]) = 0, i.e. prefix[i] == prefix[k+1]; then every j in (i, k] works.
from collections import defaultdict
def triplets(a):
    cnt = defaultdict(int); idx = defaultdict(int); cnt[0] = 1; pre = res = 0
    for k, x in enumerate(a):
        pre ^= x
        res += cnt[pre] * k - idx[pre]
        cnt[pre] += 1; idx[pre] += k + 1
    return res
print(triplets([4, 1, 5, 2, 6]), triplets([3, 3, 3, 3]))
What is printed?
  1. A. 5 6
  2. B. 2 6
  3. C. 5 4
  4. D. 5 3

Correct answer: A. 5 6

For each earlier prefix position p with the same prefix XOR as position k + 1, the segment a[p..k] XORs to 0 and contributes k − p choices of j. Summing k − p over matching p is cnt·k − Σp, kept in two maps → O(n). [4, 1, 5, 2, 6]: zero-XOR segments are [4, 1, 5] (2 splits) and [1, 5, 2, 6] (3 splits) → 5 – counting segments instead of splits gives 2. [3, 3, 3, 3]: three length-2 segments (1 each) + one length-4 segment (3) = 6. A brute force agrees.

More Coding Interview Problems questions

Exams that ask this topic