Skip to main content

๐Ÿ” Q3. Number of Unique XOR Triplets II – Explained with Optimized C++ Solution

 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], and nums[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

  1. We're interested in all unique values of the XOR of triplets.

  2. Any value in nums can itself be a valid triplet like (i, i, i).

  3. 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:

dp[k][t] = true if there exists a combination of `k` elements whose XOR is `t`

Where:

  • k ranges from 0 to 3

  • t ranges 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

class Solution { public: int uniqueXorTriplets(vector<int>& nums) { const int MAXX = 2048; // Max XOR value (2^11) int n = nums.size(); // Step 1: Remove duplicates unordered_set<int> set; for (int x : nums) { set.insert(x); } vector<int> uniqueNums(set.begin(), set.end()); // Step 2: Initialize DP table bool dp[4][MAXX] = {}; dp[0][0] = true; // Step 3: Fill the DP table for (int x : uniqueNums) { for (int k = 2; k >= 0; --k) { for (int t = 0; t < MAXX; ++t) { if (dp[k][t]) { dp[k + 1][t ^ x] = true; } } } } // Step 4: Collect all valid XORs unordered_set<int> res; for (int x : nums) { res.insert(x); // for (i, i, i) } for (int t = 0; t < MAXX; ++t) { if (dp[3][t]) { res.insert(t); } } return res.size(); } };

๐Ÿงช Dry Run Example

Input:

nums = {1, 2, 3}

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_set to remove duplicates and track results.

  • Traverse k backwards to avoid overwriting DP states.

  • Initialize dp[0][0] = true as 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

Popular posts from this blog

Maximum Difference Between Even and Odd Frequency | LeetCode

We are given a string consisting of lowercase English letters. Our task is to find the maximum difference between the frequency of two characters in the string such that: One of the characters has an even frequency . The other character has an odd frequency . The difference is calculated as:  odd_frequency - even_frequency We need to return the maximum possible difference between the odd and even frequencies. Example Walkthrough Let's take a couple of examples to better understand the problem: Example 1: Input:  s = "aaaaabbc" Frequencies: 'a' → 5 (odd) 'b' → 2 (even) 'c' → 1 (odd) Here, the maximum odd frequency is 5 (for 'a') and the maximum even frequency is 2 (for 'b'). Therefore, the result is: maxOdd - maxEven = 5 - 2 = 3 Example 2: Input:  s = "abcabcab" Frequencies: 'a' → 3 (odd) 'b' → 2 (even) 'c' → 2 (even) The maximum odd frequency is 3 (for 'a') and the maximum even fr...

Top 10 Beginner-Friendly LeetCode Questions and Their Solutions

If you're new to solving coding problems on LeetCode, it can feel overwhelming. Where do you start? Which problems are suitable for beginners? Don’t worry! In this blog post, I’ll guide you through   10 beginner-friendly LeetCode questions   that are perfect for getting started on your coding journey. These problems will help you build confidence, improve your problem-solving skills, and lay a solid foundation in data structures and algorithms. Why Start with Beginner-Friendly Problems? Before diving into advanced topics like dynamic programming or graph theory, it’s essential to: Build a strong foundation in basic programming concepts. Understand how to approach a coding problem methodically. Gain familiarity with LeetCode’s platform and its problem structure. The following problems are simple yet impactful, designed to introduce you to common techniques like loops, arrays, strings, and basic math operations. 10 Beginner-Friendly LeetCode Problems 1.  Two Sum (Easy) Prob...

Maximize Amount After Two Days of Conversions | Leetcode Question

When tackling the problem of maximizing the amount of currency after two days of conversions, we encounter an interesting graph-based problem that involves working with exchange rates between various currencies. In this article, we will explore this problem in detail, starting with the brute force approach and refining it to an optimized solution. Problem Explanation You are given a string initialCurrency (the starting currency), along with four arrays: pairs1 and rates1 : Represent exchange rates between currency pairs on Day 1. pairs2 and rates2 : Represent exchange rates between currency pairs on Day 2. The task is to maximize the amount of initialCurrency you can have after performing any number of conversions on both days. You can make conversions using Day 1 rates and then further conversions using Day 2 rates. Key Insights: Conversion rates are valid (no contradictions). Each currency can be converted back to its counterpart at a reciprocal rate (e.g., if USD -> EUR = 2....