Count Triplets That Can Form Two Arrays of Equal XOR
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
Count Triplets That Can Form Two Arrays of Equal XOR
Given an array of integers
arr. We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).Let
a = arr[i] ^ ... ^ arr[j - 1] and b = arr[j] ^ ... ^ arr[k]. Return the number of triplets (i, j, k) such that a == b.Examples
Input: arr = [2,3,1,6,7]
Output: 4
Input: arr = [1,1,1,1,1]
Output: 10
Approach 1
Level I: Brute Force (O(N^3))
Intuition
Iterate through all possible combinations of
i, j, and k. Calculate a and b for each triplet and check if they are equal.Thought Process
- Use three nested loops for
i,j, andk. - In the innermost loop, calculate XOR for
aandb. - If
a == b, incrementcount.
Pattern: Triple Nested Iteration
⏱ O(N^3) or O(N^4) - Depending on how XOR is calculated.💾 O(1) - Constant space.
Approach 2
Level II: Prefix XOR with Hash Map
Intuition
We seek such that . Instead of a nested loop, we can use a hash map to store the indices (or counts and sum of indices) where each prefix XOR has occurred.
⏱ $O(N)$💾 $O(N)$
Approach 3
Level III: Optimal (Prefix XOR)
Intuition
As shown in the logic representation, is equivalent to . Using prefix XOR array where , the XOR of is . We need . If found, all are valid.
Thought Process
- Calculate prefix XOR array
prefix. - Iterate through all pairs where :
- If
prefix[i] == prefix[k+1]:- The number of valid
j's isk - i. - Add
k - itototal.
- The number of valid
- If
Pattern: Subarray XOR Frequency
⏱ O(N^2) - Iterate through all possible $(i, k)$ pairs.💾 O(N) - Storage for prefix XOR array.
Detailed Dry Run
arr = [2, 3, 1, 6, 7]
Prefix: [0, 2, 1, 0, 6, 1]
Pairs with equal prefix values:
- P[0] and P[3]: (i=0, k=2). count += 2-0 = 2 triplets.
- P[2] and P[5]: (i=2, k=4). count += 4-2 = 2 triplets. Total: 2 + 2 = 4.
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.