Data Structures & AlgorithmsVery hardProduct company OA
Problem: Sum (a[i] XOR a[j]) over all pairs i < j in O(n · bits): at bit b, a pair contributes 2^b exactly when one value has the bit and the other does not.
Problem: Sum (a[i] XOR a[j]) over all pairs i < j in O(n · bits): at bit b, a pair contributes 2^b exactly when one value has the bit and the other does not.
def xor_pair_sum(a):
total = 0
for b in range(max(a).bit_length()):
ones = sum(x >> b & 1 for x in a)
total += ones * (len(a) - ones) << b
return total
a = [5, 9, 7, 6]
print(xor_pair_sum(a), sum(a[i] ^ a[j] for i in range(4) for j in range(i + 1, 4)))What is printed?- A. 47 47
- B. 47 94
- C. 38 47
- D. 94 94
Correct answer: A. 47 47
5 = 0101, 9 = 1001, 7 = 0111, 6 = 0110. Bit 0: three ones → 3·1 pairs × 1 = 3; bit 1: two ones → 2·2 × 2 = 8; bit 2: three → 3 × 4 = 12; bit 3: one → 3 × 8 = 24; total 47, matching the O(n²) brute force. Counting ordered pairs would double it (94). O(n log max) handles n = 2·10⁵.
More Coding Interview Problems questions
- 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]…
- 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…