Taro Logo

Number of Unique XOR Triplets II

Medium
Asked by:
Meesho
1 view
Topics:
ArraysBit Manipulation

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

Example 1:

Input: nums = [1,3]

Output: 2

Explanation:

The possible XOR triplet values are:

  • (0, 0, 0) → 1 XOR 1 XOR 1 = 1
  • (0, 0, 1) → 1 XOR 1 XOR 3 = 3
  • (0, 1, 1) → 1 XOR 3 XOR 3 = 1
  • (1, 1, 1) → 3 XOR 3 XOR 3 = 3

The unique XOR values are {1, 3}. Thus, the output is 2.

Example 2:

Input: nums = [6,7,8,9]

Output: 4

Explanation:

The possible XOR triplet values are {6, 7, 8, 9}. Thus, the output is 4.

Constraints:

  • 1 <= nums.length <= 1500
  • 1 <= nums[i] <= 1500

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the specific target outcome for the bitwise XOR operation of the triplet?
  2. Does the order of elements within the triplet matter (i.e., are $(A, B, C)$ and $(B, A, C)$ considered different triplets), or are we looking for combinations based on indices or values?
  3. How should uniqueness of the triplets be defined—are we counting distinct index combinations, or distinct value combinations when duplicate elements are present in the array?
  4. What are the size constraints of the input array and the range of values for the elements inside it?
  5. What should be returned if no such triplets can be found in the array?

Brute Force Solution

Approach

Imagine you have a collection of numbers and want to find every possible group of three that meets a specific matching rule using a combination puzzle. The brute force strategy involves testing every single possible trio combination available in your collection, one by one, to see if it satisfies the rule.

Here's how the algorithm would work step-by-step:

  1. Gather all the available numbers in front of you.
  2. Pick a first number from your collection.
  3. Pick a second number to go with the first one.
  4. Pick a third number to complete the trio.
  5. Combine these three chosen numbers together using the special math rule to see what the result is.
  6. Check if this combined result matches the target requirement for the puzzle.
  7. If the result matches, remember this trio as a successful find.
  8. Repeat this entire process by choosing every possible combination of three numbers until every single option has been tested.

Code Implementation

def count_unique_xor_triplets(number_collection, target_value):
    successful_trio_counter = 0
    total_elements = len(number_collection)

    # Iterate through all possible choices for the first element of our trio
    for first_index in range(total_elements):

        # Iterate through all subsequent elements to form a valid combination
        for second_index in range(first_index + 1, total_elements):

            # Complete the trio by checking all remaining elements in the collection
            for third_index in range(second_index + 1, total_elements):
                first_number = number_collection[first_index]
                second_number = number_collection[second_index]
                third_number = number_collection[third_index]

                combined_xor_result = first_number ^ second_number ^ third_number

                if combined_xor_result == target_value:
                    successful_trio_counter += 1

    return successful_trio_counter

Big(O) Analysis

Time Complexity
O(n³) – The brute force strategy requires picking a first number from the collection of n elements, picking a second number, and then picking a third number to form a trio. This necessitates three nested loops, where the outer loop runs n times, the middle loop runs n times, and the inner loop runs n times. Testing every possible combination of three numbers results in approximately n * n * n / 6 operations. Simplifying this polynomial yields a cubic time complexity of O(n³).
Space Complexity
O(1) – The algorithm evaluates every possible trio combination iteratively using a few primitive integer variables to track the indices and combined results. Because no auxiliary data structures like hash maps or temporary lists are allocated to store intermediate findings, the extra memory remains constant. As the input size N grows, the auxiliary space does not scale with it, resulting in a constant memory footprint. Therefore, the overall auxiliary space complexity is O(1) beyond the input itself.

Optimal Solution

Approach

Instead of checking every single possible combination of three numbers, the optimal approach relies on a clever mathematical shortcut. It pre-calculates how numbers combine and uses counting tricks to find all valid groups instantly.

Here's how the algorithm would work step-by-step:

  1. First, understand the hidden rule of the combining operation: if you combine two numbers and get a result, that result combined with either of the original numbers will always bring you right back to the other original number.
  2. Because of this balancing act, if you pick any two numbers from your collection, the exact third number needed to complete a valid trio is already completely determined.
  3. Instead of searching for that third number one by one, count how many times every possible number appears in your collection ahead of time.
  4. Go through every unique pair of numbers you can form, and figure out what their combined result would be.
  5. Check if that resulting number actually exists in your collection using your pre-counted totals.
  6. Every time you find that the needed number is available, add the total count of how many times it appears to your running score of valid trios.
  7. Finally, once all pairs have been checked, you will have your complete count without ever needing to sluggishly test every single combination by hand.

Code Implementation

from collections import Counter


def count_unique_xor_triplets(number_collection):
    frequency_map = Counter(number_collection)

    unique_numbers = list(frequency_map.keys())
    total_valid_triplets = 0

    # Pre-counting frequencies allows O(1) lookups instead of searching for the third element repeatedly.
    for index_outer in range(len(unique_numbers)):
        for index_inner in range(index_outer, len(unique_numbers)):
            first_number = unique_numbers[index_outer]
            second_number = unique_numbers[index_inner]

            required_third_number = first_number ^ second_number

            # Using XOR properties, the third number is uniquely determined by the first two numbers.
            if required_third_number in frequency_map:
                if first_number == second_number == required_third_number:
                    element_count = frequency_map[first_number]
                    total_valid_triplets += element_count * (element_count - 1) * (element_count - 2) // 6
                elif first_number == second_number:
                    element_count = frequency_map[first_number]
                    total_valid_triplets += (element_count * (element_count - 1) // 2) * frequency_map[required_third_number]
                elif first_number < second_number and second_number < required_third_number:
                    # Enforcing strict ordering prevents duplicate counting of the same triplet combination.
                    total_valid_triplets += frequency_map[first_number] * frequency_map[second_number] * frequency_map[required_third_number]

    return total_valid_triplets

Big(O) Analysis

Time Complexity
O(n²) – The time complexity is driven by iterating through every unique pair of numbers from the input collection of size n. For the first number, we check roughly n others, for the second slightly fewer, and so on. This creates nested combinations that approximate n * (n - 1) / 2 total pair checks. Since each pair check involves constant-time frequency lookups, the operations scale quadratically, which simplifies to O(n²).
Space Complexity
O(N) – To implement the pre-counted totals mentioned in step 3, the algorithm requires a hash map or frequency array to store the counts of each unique number in the collection of size N. In the worst-case scenario where all N elements are distinct, this frequency map will store N entries, resulting in linear auxiliary space relative to the input size N. Therefore, the extra memory required grows directly in proportion to the number of elements processed.

Edge Cases

Array with fewer than three elements
How to Handle:
Return zero immediately since a triplet requires at least three distinct positions.
Array containing duplicate values
How to Handle:
Ensure combinations consider index positions rather than just values to correctly count distinct triplets.
Extremely large arrays with millions of elements
How to Handle:
Use an optimized O(N^2) or frequency-based hash map approach to avoid timeout issues from naive O(N^3) nested loops.
Array with all identical elements
How to Handle:
Calculate combinations mathematically using binomial coefficients to handle large repeat counts efficiently.
Inputs containing negative numbers and zeros
How to Handle:
Bitwise operations apply standard two's complement arithmetic without requiring special sign-bit logic.
No valid triplets satisfy the XOR condition
How to Handle:
The algorithm safely iterates through all possibilities and naturally returns a final count of zero.
Integer overflow during calculations or frequency counting
How to Handle:
Use 64-bit integer types for accumulators to prevent overflow when the number of valid triplets is extremely large.