#3514
Number of Unique XOR Triplets II
MediumArrayMathBit ManipulationEnumerationHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Utilize a set to track unique XOR values while iterating through the array, reducing the need for nested loops.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a set to store unique XOR values.
- 2Step 2: Iterate through the array and compute the XOR for each element with itself and previous elements.
- 3Step 3: Add each computed XOR to the set.
solution.py7 lines
1def uniqueXORTriplets(nums):
2 unique_xors = set()
3 n = len(nums)
4 for i in range(n):
5 for j in range(i + 1):
6 unique_xors.add(nums[i] ^ nums[j])
7 return len(unique_xors)ℹ
Complexity note: The optimal solution iterates through the array with a single loop, leading to O(n) complexity.
- 1XOR is commutative and associative, allowing flexible grouping.
- 2Tracking unique values with a set prevents duplicates.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.