Are you preparing for coding interviews or contests and stumbled upon "Number of Unique XOR Triplets II"? You're in the right place. In this blog post, we’ll dive deep into this fascinating problem from LeetCode, understand what it asks, explore the logic step-by-step, and finally implement an efficient solution in C++ using Dynamic Programming (DP) and bitwise XOR.
Let’s get started!
๐ง Problem Statement
You are given a list of integers nums. Your task is to find how many distinct XOR values you can get from all triplets (i, j, k) such that:
-
i < j < k, and -
XOR of
nums[i],nums[j], andnums[k]is taken.
Additionally, triplets like (i, i, i) are valid if the number occurs at least once. So, both 3-element combinations and single elements (used as triplet) are considered.
๐ก Understanding XOR
Before diving into the solution, let’s understand XOR ( ^ ):
-
a ^ a = 0 -
a ^ 0 = a -
XOR is commutative and associative
-
Often used to find differences, toggles, and combinations in bits
๐งฉ Key Observations
-
We're interested in all unique values of the XOR of triplets.
-
Any value in
numscan itself be a valid triplet like(i, i, i). -
We must consider all 3-element combinations (without repetition) whose XOR we haven’t seen before.
⚙️ Optimal Strategy (Dynamic Programming)
Why not brute force?
Brute-forcing all possible triplets would take O(n³) time. With n ≤ 10⁵ in some cases, it’s impractical.
Dynamic Programming Insight
Let’s define a DP state:
Where:
-
kranges from 0 to 3 -
tranges from 0 to 2048 (since max XOR with 11 bits is 2048)
This approach avoids repetition and computes all possible XOR combinations efficiently.
๐ง Step-by-Step C++ Implementation
๐งช Dry Run Example
Input:
Step-by-step triplets:
-
XOR(1, 1, 1) = 1 ✅
-
XOR(2, 2, 2) = 2 ✅
-
XOR(3, 3, 3) = 3 ✅
-
XOR(1, 2, 3) = 0 ✅
Result: {0, 1, 2, 3} → Output = 4
⏱️ Time and Space Complexity
-
Time Complexity: O(n × MAXX × k) = O(n × 2048 × 3) = ~O(n)
-
Space Complexity: O(3 × 2048) = O(6144)
Very efficient even for large n.
๐ Final Thoughts
The "Number of Unique XOR Triplets II" is a great mix of bit manipulation, set theory, and dynamic programming. By converting the brute-force triple-loop into a DP table that tracks XOR states, we drastically improve performance.
๐ฅ Key Takeaways:
-
Use
unordered_setto remove duplicates and track results. -
Traverse
kbackwards to avoid overwriting DP states. -
Initialize
dp[0][0] = trueas a base case for XOR accumulation.
๐ฃ️ Let’s Discuss
Still confused about the dynamic programming transition or how XOR is used here? Drop a comment or reach out on Code Se Career – YouTube or Instagram!
๐ Tags:
XOR problems, Dynamic Programming, LeetCode Solutions, Bit Manipulation, C++ Interview Questions, Unique Triplets, DP XOR, C++ DP Problems, Competitive Programming