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
This accepted solution exploits the fact that XOR results are bounded (values up to 1500 fit within maxi = 2048), so instead of using Set objects it marks reachable XOR values with fixed-size boolean arrays: pairXor records every achievable pairwise XOR in O(n^2), and then tripletXor is filled by combining each possible pairwise XOR value (only maxi of them, not n^2) with every element of nums, giving an O(n^2 + maxi * n) runtime that comfortably fits within the limits, and the final answer is just the count of true entries in tripletXor.
/**
* @param {number[]} nums
* @return {number}
*/
var uniqueXorTriplets = function(nums) {
const maxi = 2048;
const pairXor = new Array(maxi).fill(false);
const tripletXor = new Array(maxi).fill(false);
const n = nums.length;
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
pairXor[nums[i] ^ nums[j]] = true;
}
}
for (let x = 0; x < maxi; x++) {
if (!pairXor[x]) continue;
for (const value of nums) {
tripletXor[x ^ value] = true;
}
}
return tripletXor.reduce((count, value) => count + (value ? 1 : 0), 0);
};