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

In this guide, you will get 1442. Count Triplets That Can Form Two Arrays of Equal XOR LeetCode Solution with the best time and space complexity. The solution to Count Triplets That Can Form Two Arrays of Equal XOR problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Count Triplets That Can Form Two Arrays of Equal XOR solution in C++
  4. Count Triplets That Can Form Two Arrays of Equal XOR solution in Java
  5. Count Triplets That Can Form Two Arrays of Equal XOR solution in Python
  6. Additional Resources
1442. Count Triplets That Can Form Two Arrays of Equal XOR LeetCode Solution image

Problem Statement of 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's define a and b as follows:

a = arr[i] ^ arr[i + 1] ^ … ^ arr[j – 1]
b = arr[j] ^ arr[j + 1] ^ … ^ arr[k]

Note that ^ denotes the bitwise-xor operation.
Return the number of triplets (i, j and k) Where a == b.

Example 1:

Input: arr = [2,3,1,6,7]
Output: 4
Explanation: The triplets are (0,1,2), (0,2,2), (2,3,4) and (2,4,4)

Example 2:

Input: arr = [1,1,1,1,1]
Output: 10

Constraints:

1 <= arr.length <= 300
1 <= arr[i] <= 108

Complexity Analysis

  • Time Complexity:
  • Space Complexity:

1442. Count Triplets That Can Form Two Arrays of Equal XOR LeetCode Solution in C++

class Solution:
  def countTriplets(self, arr: list[int]) -> int:
    ans = 0
    xors = [0]
    prefix = 0

    for i, a in enumerate(arr):
      prefix ^= a
      xors.append(prefix)

    for j in range(1, len(arr)):
      for i in range(0, j):
        xors_i = xors[j] ^ xors[i]
        for k in range(j, len(arr)):
          xors_k = xors[k + 1] ^ xors[j]
          if xors_i == xors_k:
            ans += 1

    return ans
/* code provided by PROGIEZ */

1442. Count Triplets That Can Form Two Arrays of Equal XOR LeetCode Solution in Java

N/A
// code provided by PROGIEZ

1442. Count Triplets That Can Form Two Arrays of Equal XOR LeetCode Solution in Python

N/A
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.