Python 1442.py
class Solution:
def countTriplets(self, arr: List[int]) -> int:
@cache
def x(a, b):
if a == b:
return arr[a]
else:
return arr[a] ^ x(a + 1, b)
result = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
for k in range(j, len(arr)):
if x(i, j - 1) == x(j, k):
result += 1
return result
Difficulty
and has an acceptance rate of about 85% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Bit Manipulation
- Hash Table
- Math
- Prefix Sum
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a class Solution with a method countTriplets that counts the number of index triplets ((i, j, k)) in an integer list arr satisfying a specific XOR equality condition. The core of the algorithm relies on a memoized recursive helper x that computes the XOR of a sub-array defined by its start and end indices. The outer part of the method iterates over all possible triples of indices using three nested loops and increments a counter whenever the equality holds.
Key Steps
Memoized XOR computation
@cache
def x(a, b):
if a == b:
return arr[a]
else:
return arr[a] ^ x(a + 1, b)
The helper x returns the XOR of the slice arr[a:b+1]. When the start and end indices coincide, the function returns the single element directly. For longer slices, it recursively XORs the first element with the result of the same function on the remainder of the slice. The @cache decorator stores previously computed results, turning the exponential recursion that would arise from overlapping sub-problems into a linear-time lookup for each distinct pair (a, b).
Triple-nested enumeration of index triples
result = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
for k in range(j, len(arr)):
if x(i, j - 1) == x(j, k):
result += 1
The outermost loop selects the leftmost index i. The middle loop picks j, which always follows i by at least one position, ensuring a non-empty left segment. The innermost loop chooses k, which can be equal to j, allowing the right segment to be a single element. For each combination, the algorithm compares the XOR of the left segment arr[i:j] (computed as x(i, j - 1)) with the XOR of the right segment arr[j:k+1] (computed as x(j, k)). When the two values match, the counter result is incremented.
Return of the final count
return result
After all possible triples have been examined, the method returns the accumulated count.
Edge Cases Handled
When the input list arr contains a single element, the outer loop runs once, the middle loop does not execute because i + 1 equals the length of the list, and consequently the innermost loop is never entered. The method therefore returns zero, which correctly reflects the impossibility of forming a triplet in a one-element array.
If arr is empty, the range generated by len(arr) is empty, so none of the loops execute and the method again returns zero. The recursive helper x is never invoked, avoiding any attempt to access an out-of-range index.
When j equals k, the right segment reduces to a single element. The call x(j, k) then triggers the base case a == b, returning that element directly. This situation is explicitly supported by the recursion and does not require special handling elsewhere.
The base case a == b in the helper also safeguards against infinite recursion. By returning the element at the exact index, the recursion terminates cleanly for any valid sub-array, including those of length one that arise from the enumeration logic.
Performance Optimizations Observed
The most significant optimization is the use of the @cache decorator on the recursive XOR function. Without caching, each call to x would recompute the XOR of overlapping sub-arrays many times, leading to redundant work. Caching ensures that each distinct pair of indices (a, b) is evaluated at most once, after which the stored result is retrieved in constant time for any subsequent request. This dramatically reduces the total number of XOR operations performed across the three nested loops.
Additionally, the recursive definition of x builds the XOR result incrementally from the leftmost element toward the right. By reusing previously computed suffix XORs, the function avoids recomputing the entire segment from scratch each time a new start index is considered. This incremental approach, combined with memoization, yields a practical performance profile despite the cubic enumeration of index triples.
ELI5 - Simplified Explanation
Imagine a long row of numbered blocks sitting on a table. To play this game, three little markers are placed along the row to pick out different sections of the blocks. The first marker picks a starting chunk, the second marker picks the middle point, and the third marker picks an ending point.
The goal of the game is to compare the value of the chunk between the first and second markers with the value of the chunk between the second and third markers. The value of a chunk is found by combining all the numbers in that space using a special rule that flips bits around like magic. Every time the numbers from the left side and the numbers from the right side match perfectly, a tally mark is added to a scoreboard to keep track of the wins. The code simply looks at every possible way to line up those three markers along the row to see how many times the two sides end up being exactly the same. There is even a clever trick used to remember the values of chunks that have already been looked at so the work does not have to be done all over again.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | Python | |||||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | ||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| wisdompeak | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | Python | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1400: Construct K Palindrome Strings
- problem 1519: Number of Nodes in the Sub-Tree With the Same Label
- problem 1577: Number of Ways Where Square of Number Is Equal to Product of Two Numbers
- problem 1593: Split a String Into the Max Number of Unique Substrings
- problem 1604: Alert Using Same Key-Card Three or More Times in a One Hour Period
- problem 1638: Count Substrings That Differ by One Character
- problem 1695: Maximum Erasure Value
- problem 1726: Tuple with Same Product
- problem 1368: Minimum Cost to Make at Least One Valid Path in a Grid
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality