Number of Unique XOR Triplets I Problem
Description
LeetCode Problem 3513.
You are given an integer array nums of length n, where nums is a permutation of the numbers in the range [1, n].
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,2]
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 2 = 2
- (0, 1, 1) → 1 XOR 2 XOR 2 = 1
- (1, 1, 1) → 2 XOR 2 XOR 2 = 2
The unique XOR values are {1, 2}, so the output is 2.
Example 2:
Input: nums = [3,1,2]
Output: 4
Explanation:
The possible XOR triplet values include:
- (0, 0, 0) → 3 XOR 3 XOR 3 = 3
- (0, 0, 1) → 3 XOR 3 XOR 1 = 1
- (0, 0, 2) → 3 XOR 3 XOR 2 = 2
- (0, 1, 2) → 3 XOR 1 XOR 2 = 0
The unique XOR values are {0, 1, 2, 3}, so the output is 4.
Constraints:
1 <= n == nums.length <= 10^51 <= nums[i] <= nnumsis a permutation of integers from1ton.
Solution
Approach: Bit Manipulation
Because i <= j <= k allows equal indices, a triplet is any three numbers from 1..n chosen with repetition, and we count the distinct XOR values.
For n = 1 the only value is 1, and for n = 2 the values are 1 and 2, so the answer equals n. For n >= 3 the XOR values fill the whole range [0, 2^b - 1], where 2^b is the smallest power of two greater than n, which is 1 << bitLength(n). For example, n = 3 has bit length 2, so the answer is 4, matching the set {0, 1, 2, 3}.
Complexity: O(1) time and O(1) extra space.
class Solution:
def uniqueXorTriplets(self, nums: List[int]) -> int:
n = len(nums)
return n if n <= 2 else 1 << n.bit_length()