Number of Unique XOR Triplets II - Problem

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).

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,3,1,4]
Output: 8
💡 Note: All possible XOR triplets: (0,0,0)→2, (0,0,1)→3, (0,0,2)→1, (0,0,3)→4, (0,1,1)→2, (0,1,2)→0, (0,1,3)→5, (0,2,2)→2, (0,2,3)→7, (0,3,3)→2, (1,1,1)→3, (1,1,2)→1, (1,1,3)→4, (1,2,2)→3, (1,2,3)→6, (1,3,3)→3, (2,2,2)→1, (2,2,3)→4, (2,3,3)→1, (3,3,3)→4. Unique values: {0,1,2,3,4,5,6,7} = 8 different values.
Example 2 — Small Array
$ Input: nums = [1,2]
Output: 2
💡 Note: All triplets: (0,0,0)→1, (0,0,1)→2, (0,1,1)→1, (1,1,1)→2. Unique values: {1,2} = 2 different values.
Example 3 — Identical Elements
$ Input: nums = [5,5,5]
Output: 1
💡 Note: All triplets use three 5's in various combinations, but since XOR of any odd number of identical values equals the value itself, all results equal 5. Unique values: {5} = 1 different value.

Constraints

  • 3 ≤ nums.length ≤ 1000
  • 0 ≤ nums[i] ≤ 216

Visualization

Tap to expand
Number of Unique XOR Triplets II INPUT nums array: 2 i=0 3 i=1 1 i=2 4 i=3 XOR Triplet: nums[i] XOR nums[j] XOR nums[k] where i <= j <= k Example Triplets: (0,0,0): 2 XOR 2 XOR 2 = 2 (0,1,2): 2 XOR 3 XOR 1 = 0 (0,1,3): 2 XOR 3 XOR 4 = 5 (1,2,3): 3 XOR 1 XOR 4 = 6 Find all UNIQUE XOR values from valid triplets ALGORITHM STEPS 1 Pass 1: Compute Pairs Store all nums[i] XOR nums[j] pairs in a Set 2 Pass 2: XOR with Third For each pair, XOR with each nums[k] where k >= j 3 Collect Unique Values Store triplet XOR results in result Set 4 Return Count Return size of result Set Pair XOR Values (Pass 1): 2^2=0, 2^3=1, 2^1=3, 2^4=6 3^3=0, 3^1=2, 3^4=7 1^1=0, 1^4=5, 4^4=0 Pairs: {0,1,2,3,5,6,7} FINAL RESULT All Unique XOR Triplet Values: 0 1 2 3 4 5 6 OUTPUT 7 7 unique XOR values found Verification [OK] Set size = 7 unique values {0, 1, 2, 3, 4, 5, 6} Key Insight: Two-Pass Preprocessing avoids O(n^3) by first computing all pair XORs, then combining with third element. Using Sets automatically handles duplicates. XOR properties: a^a=0, a^0=a, and XOR is commutative/associative. TutorialsPoint - Number of Unique XOR Triplets II | Two-Pass with Pair Preprocessing
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen