DEV Community

Karleb
Karleb

Posted on

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

https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/solutions/5228488/98-33-easy-solution-with-explanation/?envType=daily-question&envId=2024-05-30


/**
 * @param {number[]} arr
 * @return {number}
 */
var countTriplets = function (arr) {
    let n = arr.length
    let prefix = new Array(n + 1).fill(0)

    for (i = 0; i < n; i++) {
        prefix[i + 1] = prefix[i] ^ arr[i]
    }

    let count = 0

    for (let i = 0; i < n; i++) {
        for (let k = i + 1; k < n; k++) {
            if (prefix[i] === prefix[k + 1]) {
                count += (k - i)
            }
        }
    }

    return count
};


Enter fullscreen mode Exit fullscreen mode

Top comments (0)