Skip to content

2425. Bitwise XOR of All Pairings 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  int xorAllNums(vector<int>& nums1, vector<int>& nums2) {
    // If the size of nums1 is m and the size of nums2 is n, then each number in
    // nums1 is repeated n times and each number in nums2 is repeated m times.
    const int xors1 = accumulate(nums1.begin(), nums1.end(), 0, bit_xor<>());
    const int xors2 = accumulate(nums2.begin(), nums2.end(), 0, bit_xor<>());
    return (nums1.size() % 2 * xors2) ^ (nums2.size() % 2 * xors1);
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public int xorAllNums(int[] nums1, int[] nums2) {
    // If the size of nums1 is m and the size of nums2 is n, then each number in
    // nums1 is repeated n times and each number in nums2 is repeated m times.
    final int xors1 = Arrays.stream(nums1).reduce((a, b) -> a ^ b).getAsInt();
    final int xors2 = Arrays.stream(nums2).reduce((a, b) -> a ^ b).getAsInt();
    return (nums1.length % 2 * xors2) ^ (nums2.length % 2 * xors1);
  }
}
1
2
3
4
5
6
7
class Solution:
  def xorAllNums(self, nums1: list[int], nums2: list[int]) -> int:
    xors1 = functools.reduce(operator.xor, nums1)
    xors2 = functools.reduce(operator.xor, nums2)
    # If the size of nums1 is m and the size of nums2 is n, then each number in
    # nums1 is repeated n times and each number in nums2 is repeated m times.
    return (len(nums1) % 2 * xors2) ^ (len(nums2) % 2 * xors1)