2425: Bitwise-XOR-of-All-Pairings
Medium
table of contents
There are 2 key parts in the question:
Using both these properties, if we take the first example where:
nums1 = [2, 1, 3]
nums2 = [10, 2, 5, 0]
We find that a possible nums3
, which contains the
bitwise XOR of all pairings between nums1
and nums2
, is [8,0,7,2,11,3,4,1,9,1,6,3]
.
However, when we try return the bitwise XOR of
all integers in nums3
, since we know that each element
in nums3
is just the result of a XOR operation between an
element in nums1
and nums2
, it means that
8 ^ 0 ^ 7 ^ 2 ^ 11 ^ 3 ^ 4 ^ 1 ^ 9 ^ 1 ^ 6 ^ 3
is
equivalent to
(2 ^ 10) ^ (2 ^ 2) ^ (2 ^ 5) ^ (2 ^ 0) ^ (1 ^ 10) ^ (1 ^ 2) ^ (1 ^ 5) ^ (1 ^ 0) ^ ...
etc.
You may notice immediately that there is a pattern; the number of a times you bitwise XOR an element is equal to the number of elements in the opposite array;
e.g. (*2* ^ 10) ^ (*2* ^ 2) ^ (*2* ^ 5) ^ (*2* ^ 0) ^ (1 ^ 10) ^ (1 ^ 2) ^ ...
etc. you see that you have to bitwise XOR nums1[0] = 2
4 times as nums2.size() = 4
.
Since order does not matter, we can rearrange the expression:
Following this, we realise that bitwise XORing an element times is equivalent to bitwise XORing an element times.
Therefore, my algorithm is to check for the length
of both nums1
and nums2
;
Then, there are 3 outcomes:
code
class Solution {
public:
int xorAllNums(vector<int>& nums1, vector<int>& nums2) {
int temp1 = 0, temp2 = 0;
if (nums1.size()%2 == 1) {
= nums3[0];
temp2 for (int i = 1; i < nums2.size(); ++i) {
^= nums2[i];
temp2 }
}
if (nums2.size()%2 == 1) {
= nums1[0];
temp1 for (int i = 1; i < nums1.size(); ++i) {
^= nums1[i];
temp1 }
}
int ans = temp1 ^ temp2;
return ans;
}
};