Problem 1442

Abstract / Summary

Count the number of index triplets where the xor of the three elements can be split into two groups with the same xor value.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
17 lines | 486 bytes | submitted December 8, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 85% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • Hash Table
  • Math
  • Prefix Sum
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 4 | μ = 4.96 | σ = 1.93

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
27 links | 17 authors | 9 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

10 solutions   December 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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