Data Structures & AlgorithmsHardGoogle · Flipkart interview
Problem: Sum a[i] XOR a[j] over all pairs i < j in O(n · bits) by counting, for each bit, how many numbers have it set.
Problem: Sum a[i] XOR a[j] over all pairs i < j in O(n · bits) by counting, for each bit, how many numbers have it set.
def pair_xor(a):
total = 0
for b in range(31):
ones = sum(x >> b & 1 for x in a)
total += ones * (len(a) - ones) << b
return total
print(pair_xor([5, 9, 14, 3]))What is printed?- A. 26
- B. 59
- C. 48
- D. 31
Correct answer: B. 59
A bit contributes 2^b once for each pair where exactly one number has it: ones × zeros pairs. For [5, 9, 14, 3] that sums to 59, matching the six pairwise XORs added directly.
More Coding Interview Problems questions
- Edge case: nCr mod p is computed with factorials and Fermat inverses. Here n ≥ p. python p = 7 fact = [1] 11 for i in range(1, 11)…
- Problem: Extended Euclid returns g = gcd(a, b) and integers x, y with a·x + b·y = g. python def eg(a, b): if b == 0: return a, 1, 0 g, x…
- Problem: A segment tree with lazy propagation supports 'add v to a[l..r]' and 'sum of a[l..r]' on an array of 8 zeros. python N = 8 t, lz…
- Problem: Count inversions (i < j, a[i] > a[j]) with a Fenwick tree over values, scanning from the right. python def inversions(a): n =…
- Problem: Return the longest word that can be built one letter at a time from other words in the list (every prefix must be present); ties…
- Problem: s1[i] and s2[i] are declared equivalent letters (the relation is reflexive, symmetric and transitive). Replace every letter of…