#3513

Number of Unique XOR Triplets I

Medium
ArrayMathBit ManipulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal 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
  1. 1Step 1: Initialize a set to store unique XOR values.
  2. 2Step 2: Iterate through all possible combinations of three numbers in the range [1, n].
  3. 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.