3514. Number of Unique XOR Triplets II
Description
You are given an integer array nums.
A XOR triplet is defined as the XOR of three elements nums[i] XOR nums[j] XOR nums[k] where i <= j <= k.
Return the number of unique XOR triplet values from all possible triplets (i, j, k).
Β
Example 1:
Input: nums = [1,3]
Output: 2
Explanation:
The possible XOR triplet values are:
(0, 0, 0) β 1 XOR 1 XOR 1 = 1(0, 0, 1) β 1 XOR 1 XOR 3 = 3(0, 1, 1) β 1 XOR 3 XOR 3 = 1(1, 1, 1) β 3 XOR 3 XOR 3 = 3
The unique XOR values are {1, 3}. Thus, the output is 2.
Example 2:
Input: nums = [6,7,8,9]
Output: 4
Explanation:
The possible XOR triplet values are {6, 7, 8, 9}. Thus, the output is 4.
Β
Constraints:
1 <= nums.length <= 15001 <= nums[i] <= 1500
Solutions
Solution 1: Enumeration
With indices satisfying \(i \le j \le k\), the same index may be chosen more than once, and XOR is commutative. Therefore, the answer equals the number of distinct XOR values obtainable by picking any three elements from the array (with replacement).
Let \(M = \max(\textit{nums})\). The XOR of any two non-negative integers at most \(M\) is less than \(2M\), so a boolean array of length \(2M\) can be used for marking.
First enumerate all pairs \((a, b)\) and mark \(a \oplus b\) in array \(\textit{st}\). Then enumerate every appeared pairwise XOR value \(\textit{ab}\) and each third element \(c\), and mark \(\textit{ab} \oplus c\) in array \(s\). Finally count the number of non-zero entries in \(s\).
The time complexity is \(O(n^2 + M \cdot n)\), and the space complexity is \(O(M)\), where \(n\) is the length of the array and \(M\) is the maximum value in the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |