cswork / libraryOpen practice workspace

Interview questions · IBM

Sum the XOR of Every Cross-Array Pair

Compute the sum of XOR values across every pair drawn from two integer arrays without enumerating the full Cartesian product. The problem tests bit-frequency reasoning, duplicate handling, and overflow-safe accumulation under large input limits.

You are given two integer arrays, a and b. For every ordered cross-array pair (a[i], b[j]), compute a[i] XOR b[j] and return the sum of all those results.

Implement sumPairwiseXor(a, b).

Input and Output

  • a and b are arrays of non-negative integers.
  • Return one integer equal to ∑i=0∣a∣−1∑j=0∣b∣−1(a[i]XORb[j])\sum_{i=0}^{|a|-1}\sum_{j=0}^{|b|-1}(a[i]\mathbin{\mathrm{XOR}}b[j]).
  • Pair positions are counted separately, so repeated values still contribute once for every index pair.

Constraints

  • 1 <= a.length, b.length <= 50,000
  • 0 <= a[i], b[j] <= 1,000,000,000
  • The result fits in a signed 64-bit integer.
  • An approach that enumerates every pair will not finish within the intended limits.

Example 1

Input: a = [1, 2], b = [3, 4]
Output: 14

The four XOR values are 2, 5, 1, and 6.

Example 2

Input: a = [0, 7], b = [1, 7, 8]
Output: 37

The six XOR values are 1, 7, 8, 6, 0, and 15.

Community answers

Nothing here yet.

Join in on CSWork →