../ Competitive Programming
-rw-r--r--aguang1.2 KiB1 min read

Leet Code Daily 2024-05-30 - Count Triplets That Can Form Two Arrays of Equal XOR

Solution

Preffix Sum + Hash

First, let's define preffix sum under XOR operator:

Si={0i=0Si−1⊕Ai−11≤i≤nS_{i} = \begin{cases} 0 & i = 0 \\ S_{i - 1} \oplus A_{i - 1} & 1 \leq i \leq n \\ \end{cases}

Then we know, for any valid triplet (i, j, k):

Sj⊕Si=Sk+1⊕SjSi=Sk+1\begin{align} S_{j} \oplus S_{i} &= S_{k + 1} \oplus S_{j} \\ S_{i} &= S_{k + 1} \\ \end{align}

We know 0<=i<j<=k<n0 <= i < j <= k < n; so for any i,ki, k where Si=Sk+1S_{i} = S_{k + 1}, there are k−ik - i possible jj values.

Then we can hash SiS_{i} to count them in O(n)O(n) time.

Code

c++
class Solution {
public:
    int countTriplets(vector<int>& arr) {
        vector<int> s = {0};
        for (const auto& a : arr) {
            s.push_back(s.back() ^ a);
        }
        int ans = 0;
        unordered_map<int, int> cnt, sum;
        for (int i = 0; i < arr.size(); i++) {
            ans += cnt[s[i + 1]] * i - sum[s[i + 1]];
            cnt[s[i]]++;
            sum[s[i]] += i;
        }
        return ans;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window