Count Triplets That Can Form Two Arrays of Equal XOR — LeetCode 1442 Python Solution
MediumBit ManipulationArrayHash TableMathPrefix Sum
- Problem
- #1442
- Pattern
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n^2), where n is the length of the array \textit{arr} |
| Space | O(1) auxiliary |
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
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(n^2), 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.