Number of Unique XOR Triplets I - Problem

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

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,2,3]
Output: 4
💡 Note: All possible triplets: (0,0,0):1⊕1⊕1=1, (0,0,1):1⊕1⊕2=2, (0,0,2):1⊕1⊕3=3, (0,1,1):1⊕2⊕2=1, (0,1,2):1⊕2⊕3=0, (0,2,2):1⊕3⊕3=1, (1,1,1):2⊕2⊕2=2, (1,1,2):2⊕2⊕3=3, (1,2,2):2⊕3⊕3=2, (2,2,2):3⊕3⊕3=3. Unique values are {0,1,2,3}, so answer is 4.
Example 2 — Smaller Array
$ Input: nums = [2,1]
Output: 2
💡 Note: Possible triplets: (0,0,0):2⊕2⊕2=2, (0,0,1):2⊕2⊕1=1, (0,1,1):2⊕1⊕1=2, (1,1,1):1⊕1⊕1=1. Unique values are {1,2}, so answer is 2.
Example 3 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Only one triplet possible: (0,0,0):1⊕1⊕1=1. Unique values are {1}, so answer is 1.

Constraints

  • 1 ≤ nums.length ≤ 300
  • nums is a permutation of [1, 2, ..., n]

Visualization

Tap to expand
Number of Unique XOR Triplets I INPUT Permutation array nums[] 1 i=0 2 i=1 3 i=2 XOR Triplet Definition: nums[i] XOR nums[j] XOR nums[k] where i <= j <= k Constraints: n = 3 (array length) Values: permutation of [1,n] Find: unique XOR values Input Array: nums = [1, 2, 3] ALGORITHM STEPS 1 Initialize Set Create set for unique XOR values 2 Generate Triplets Loop: i <= j <= k 3 Compute XOR Add result to set 4 Return Count Size of unique set All Triplet XOR Values: 1^1^1=1 1^1^2=2 1^1^3=3 1^2^2=1 1^2^3=0 1^3^3=1 2^2^2=2 2^2^3=3 2^3^3=2 3^3^3=3 Unique: {0, 1, 2, 3} Early termination optimizes! FINAL RESULT Unique XOR Values Found: 0 1 2 3 Total Unique Count: 4 OK - Verified! 4 unique XOR triplet values Output: 4 Key Insight: XOR properties: a^a=0, a^0=a. With early termination, we can skip redundant calculations when a pattern emerges. For permutations [1,n], the unique XOR count depends on n's properties. Time complexity optimized from O(n^3) to better with smart early termination strategies. TutorialsPoint - Number of Unique XOR Triplets I | Optimized with Early Termination
Asked in
Microsoft 15 Google 12 Meta 8
8.3K Views
Medium Frequency
~15 min Avg. Time
156 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