#3513
Number of Unique XOR Triplets I
MediumArrayMathBit ManipulationHash 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 the properties of XOR and the range of numbers to derive all possible XOR values without generating triplets.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a set to store unique XOR values.
- 2Step 2: Iterate through all possible combinations of three numbers in the range [1, n].
- 3Step 3: Calculate the XOR for each combination and add it to the set.
solution.py8 lines
1def uniqueXORTriplets(nums):
2 unique_xors = set()
3 n = len(nums)
4 for i in range(1, n + 1):
5 for j in range(i, n + 1):
6 for k in range(j, n + 1):
7 unique_xors.add(i ^ j ^ k)
8 return len(unique_xors)ℹ
Complexity note: We only iterate through the range [1, n] and leverage the properties of XOR, reducing complexity.
- 1XOR of identical numbers is 0.
- 2XOR is commutative and associative.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.