#1442
Count Triplets That Can Form Two Arrays of Equal XOR
MediumArrayHash TableMathBit ManipulationPrefix SumHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution leverages the properties of XOR and prefix sums to reduce the time complexity. By using a hashmap to store the frequency of prefix XOR values, we can efficiently count valid triplets without needing nested loops.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a hashmap to store the frequency of prefix XOR values and a variable to keep track of the current prefix XOR.
- 2Step 2: Iterate through the array and calculate the prefix XOR while updating the hashmap.
- 3Step 3: For each prefix XOR value, check if it has been seen before. If it has, it means there are valid triplets that can be formed with the current index.
- 4Step 4: Count the number of valid triplets based on the frequency of the prefix XOR values.
- 5Step 5: Return the total count of valid triplets.
solution.py17 lines
1# Full working Python code
2
3def countTriplets(arr):
4 count = 0
5 prefix_xor = 0
6 freq = {0: 1}
7 for num in arr:
8 prefix_xor ^= num
9 if prefix_xor in freq:
10 count += freq[prefix_xor]
11 freq[prefix_xor] += 1
12 else:
13 freq[prefix_xor] = 1
14 return count
15
16# Example usage:
17print(countTriplets([2, 3, 1, 6, 7])) # Output: 4ℹ
Complexity note: The time complexity is O(n) because we make a single pass through the array. The space complexity is O(n) due to the hashmap storing prefix XOR values.
- 1Using prefix XOR helps in reducing the problem to counting occurrences of XOR values.
- 2The properties of XOR (a ^ a = 0) allow us to find subarrays with equal XOR efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.