16.01.2025
2425. Bitwise XOR of All Pairings medium blog post substack youtube deep-dive
Join me on Telegram
Problem TLDR
Xor of all pairs xors #medium #xor
Intuition
Observe the all pairs xor:
// 2 1 3
// 10 2 5 0
// 2^10 2^2 2^5 2^0
// 1^10 1^2 1^5 1^0
// 3^10 3^2 3^5 3^0
Even size will reduce other array to 0.
Approach
we can use a single variable
Complexity
Time complexity: O(n)
Space complexity: O(1)
Code
fun xorAllNums(nums1: IntArray, nums2: IntArray) =
nums1.reduce(Int::xor) * (nums2.size % 2) xor
nums2.reduce(Int::xor) * (nums1.size % 2)
pub fn xor_all_nums(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
let mut r = 0;
if nums2.len() % 2 > 0 { for x in &nums1 { r ^= x }}
if nums1.len() % 2 > 0 { for x in &nums2 { r ^= x }}; r
}
int xorAllNums(vector<int>& nums1, vector<int>& nums2) {
int r = 0;
if (nums2.size() % 2) for (int x: nums1) r ^= x;
if (nums1.size() % 2) for (int x: nums2) r ^= x;
return r;
}