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?- A. 5 6
- B. 2 6
- C. 5 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
- Problem: Write an integer in base −2 (digits 0/1, place values 1, −2, 4, −8, …). When Python's divmod by −2 gives a negative remainder…
- Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses: remember at which output position each remainder…
- Problem: Fibonacci numbers modulo m repeat with the Pisano period π(m). Use it to get F(10¹⁸) mod 10 without big loops. python def…
- Problem: Compute 3^(5^20) mod p for the prime p = 10⁹ + 7. By Fermat, exponents can be reduced modulo p − 1 (since gcd(3, p) = 1). Which…
- Problem: Two equal-length strings over {x, y}; one move swaps s1[i] with s2[j] (any i, j). Minimum moves to make them equal (−1 if…
- Problem: Rabin–Karp search with a rolling hash: (a) base 10, modulus 7; (b) base 256, modulus 1000003. Count true matches and spurious…