Count Triplets That Can Form Two Arrays of Equal XOR

Reduces to counting (i, k) pairs with prefix XOR equal — sum (k - i) for each such pair.

Medium
Time O(n^2) simple Space O(n)
LeetCode
4 min read
bit-manipulation prefix-xor hash-map

Problem#

Count triplets (i, j, k) with i < j <= k such that XOR(arr[i..j-1]) == XOR(arr[j..k]).

Examples#

  • [2,3,1,6,7]4.
  • [1,1,1,1,1]10.

Constraints#

  • 1 <= arr.length <= 300, 1 <= arr[i] <= 10^8.

Approach#

Let p be the prefix-XOR array (p[0] = 0). The condition reduces to p[i] == p[k+1]. For any such pair (i, k), every j with i < j <= k works — that’s k - i triplets.

Solution#

Count Triplets That Can Form Two Arrays of Equal XOR
class Solution {
public:
int countTriplets(vector<int>& arr) {
int n = arr.size();
vector<int> p(n + 1, 0);
for (int i = 0; i < n; ++i) p[i + 1] = p[i] ^ arr[i];
int ans = 0;
for (int i = 0; i <= n; ++i)
for (int k = i + 1; k <= n; ++k)
if (p[i] == p[k]) ans += (k - i - 1);
return ans;
}
};

Editorial#

XOR(a..b) reduces to p[a] ^ p[b+1]. The two halves being equal means their combined XOR is 0, i.e., p[i] == p[k+1]. Once that holds, the split point j is free anywhere in (i, k], contributing k - i triplets.

Complexity#

  • Time: O(n^2) straightforward; O(n) with a hashmap tracking last positions and counts.
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.