MediumNo. 1442
Count Triplets That Can Form Two Arrays of Equal XOR — LeetCode 1442 Python Solution
- Pattern
- Prefix Sum
- Topics
- Bit Manipulation, Array, Hash Table, Math, Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given an array of integers arr. We want to select three indices i, j and k where (0 <= i < j <= k < arr.length).
Example
- 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)
Python solution
class Solution:
def countTriplets(self, arr: List[int]) -> int:
ans, n = 0, len(arr)
for i, x in enumerate(arr):
s = x
for k in range(i + 1, n):
s ^= arr[k]
if s == 0:
ans += k - i
return ansComplexity
- Time
- O(n2)where n is the length of the array arr
- Space · auxiliary
- O(1)
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 1442. Count Triplets That Can Form Two Arrays of Equal XOR is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0268 | Missing Number | Easy |
| 0523 | Continuous Subarray Sum | Medium |
| 0996 | Number of Squareful Arrays | Hard |
| 1177 | Can Make Palindrome from Substring | Medium |
| 1248 | Count Number of Nice Subarrays | Medium |
| 1994 | The Number of Good Subsets | Hard |
Frequently asked questions
- How hard is LeetCode 1442. Count Triplets That Can Form Two Arrays of Equal XOR?
LeetCode 1442. Count Triplets That Can Form Two Arrays of Equal XOR is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1442. Count Triplets That Can Form Two Arrays of Equal XOR?
The Python solution on this page runs in O(n2), where n is the length of the array \textit{arr}.
- What is the space complexity of LeetCode 1442. Count Triplets That Can Form Two Arrays of Equal XOR?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1442. Count Triplets That Can Form Two Arrays of Equal XOR cover?
LeetCode 1442. Count Triplets That Can Form Two Arrays of Equal XOR is tagged Bit Manipulation, Array, Hash Table, Math and Prefix Sum on LeetCode.