Number of Unique XOR Triplets II Problem
Description
LeetCode Problem 3514.
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
Solution
Approach: Enumeration with Marking
Since indices may repeat and XOR is commutative, we only need the set of distinct values a ^ b ^ c with a, b, c taken from the array with repetition.
Let M be the largest value. Every XOR of two numbers not greater than M is below 2M, so a boolean array of that size is enough. First mark a ^ b for all pairs. Then for each marked value ab and each element c, mark ab ^ c. The answer is the number of marked values in the second array.
Complexity: O(n2 + M * n) time and O(M) extra space, where n is the array length and M the maximum value.
class Solution:
def uniqueXorTriplets(self, nums: List[int]) -> int:
mx = max(nums) << 1
st = [False] * mx
for a in nums:
for b in nums:
st[a ^ b] = True
s = [0] * mx
for ab in range(mx):
if st[ab]:
for c in nums:
s[ab ^ c] = 1
return sum(s)