Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1442. Count Triplets That Can Form Two Arrays of Equal XOR

Explanation

To solve this problem, we can iterate through all possible triplets (i, j, k) and calculate the values of a and b. We then check if a == b for each triplet and count the valid triplets. The key observation here is that a == b is equivalent to arr[i] ^ ... ^ arr[j] == arr[j] ^ ... ^ arr[k].

We can precalculate the XOR prefix sums of the given array to efficiently calculate the XOR of any subarray. Using this, we can iterate through all possible pairs of indices (i, j) and use a hashmap to store the count of XOR values encountered so far. Then, for each valid k, we check if arr[i] ^ ... ^ arr[j] == arr[j] ^ ... ^ arr[k] and increment the count accordingly.

Time Complexity: O(n) where n is the length of the input array arr. Space Complexity: O(n) for the hashmap to store XOR values.

class Solution {
    public int countTriplets(int[] arr) {
        int n = arr.length;
        int[] xorPrefix = new int[n + 1];
        for (int i = 0; i < n; i++) {
            xorPrefix[i + 1] = xorPrefix[i] ^ arr[i];
        }
        
        int count = 0;
        Map<Integer, Integer> xorCount = new HashMap<>();
        
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                int a = xorPrefix[i] ^ xorPrefix[j];
                if (xorCount.containsKey(a)) {
                    count += xorCount.get(a);
                }
                if (xorPrefix[j] == xorPrefix[i]) {
                    count++;
                }
                xorCount.put(xorPrefix[j], xorCount.getOrDefault(xorPrefix[j], 0) + 1);
            }
        }
        
        return count;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.