Problem
You are given two 0-indexed arrays, nums1
and nums2
, consisting of non-negative integers. There exists another array, nums3
, which contains the bitwise XOR of all pairings of integers between nums1
and nums2
(every integer in nums1
is paired with every integer in nums2
exactly once).
Return the bitwise XOR of all integers in nums3
.
Examples
Example 1:
|
|
Example 2:
|
|
Constraints:
1 <= nums1.length, nums2.length <= 105
0 <= nums1[i], nums2[j] <= 109
Solution
Video explanation
Here is the video explaining this method in detail. Please check it out:
Method 1 - Naive
The naive approach involves directly computing the XOR of all pairings between elements of nums1
and nums2
, just as described in the problem statement.
Here is the approach:
- Initialize a variable to store the result of XORs, starting with
0
. - Iterate through each element in
nums1
. - For each element in
nums1
, iterate through each element innums2
. - Compute the bitwise XOR of the current pair and update the result by XORing it with the computed value.
- Return the final result after iterating through all pairings.
Pseudocode
|
|
Complexity
- ⏰ Time complexity:
O(m * n)
, wherem
is the length ofnums1
andn
is the length ofnums2
. This is because we have an outer loop iterating overnums1
and an inner loop iterating overnums2
, resulting inm * n
iterations. - 🧺 Space complexity:
O(1)
Method 2 - Optimal
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(m + n)
, wherem
is the length ofnums1
andn
is the length ofnums2
. This is because we need to iterate through both arrays once to compute their XORs. - 🧺 Space complexity:
O(1)
, as we are utilizing only a constant amount of extra space for storing the XOR values and intermediate results.