Problem 1310

Abstract / Summary

Given an array and multiple queries, compute the xor of elements in each specified subarray.

Note

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

Python 1310.py

class Solution:
    def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
        # similar to a prefix sum, but XOR instead of +
        zorro = [ 0 ] # zorro[i] = arr[0] ^ arr[1] ^ ... ^ arr[i - 1]
        for a in arr:
            zorro.append(a ^ zorro[-1])

        return [ zorro[left] ^ zorro[right + 1] for left, right in queries ]
8 lines | 371 bytes | submitted January 9, 2024 | GitHub   33% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 78% (200k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Bit Manipulation
  • 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 xorQueries method receives an integer list arr and a list of query intervals queries. For each interval [left, right] it returns the cumulative XOR of the sub-array arr[left] … arr[right]. The implementation follows the classic prefix-XOR technique: a running XOR is stored for every prefix of the input array, and each query is answered by XOR-ing two prefix values.

Key Steps

The first phase constructs a prefix-XOR array named zorro. The array is initialized with a zero so that zorro[i] represents the XOR of the first i elements of arr. The loop iterates over arr, appending the XOR of the current element with the last entry of zorro.

zorro = [0]                     # zorro[i] = arr[0] ^ … ^ arr[i-1]
for a in arr:
    zorro.append(a ^ zorro[-1])

After the prefix array is ready, the method processes each query. For a query [left, right] the XOR of the sub-array is obtained by XOR-ing the prefix up to right + 1 with the prefix up to left. The list comprehension builds the result list in a single expression.

return [zorro[left] ^ zorro[right + 1] for left, right in queries]

Edge Cases Handled

When arr is empty the prefix array contains only the initial zero, and any query would be invalid; the code implicitly returns an empty result list because the comprehension iterates over queries.

If a query asks for a single element (left == right) the expression reduces to zorro[left] ^ zorro[left + 1], which equals the element itself, correctly handling the minimal interval.

Queries that span the entire array (left == 0 and right == len(arr) - 1) use zorro[0] (zero) and zorro[len(arr)], yielding the XOR of the whole list.

The implementation also tolerates queries where right is the last index because right + 1 safely accesses the extra sentinel element appended to zorro.

Performance Optimizations

The prefix-XOR construction runs in linear time relative to the length of arr, and each query is answered in constant time by a single XOR operation. This eliminates the need for recomputing XOR over the same ranges repeatedly.

Storing the prefix values in a plain Python list provides fast index access and low overhead. The final result is generated with a list comprehension, which is implemented in C and therefore faster than an explicit Python loop.

Using the XOR operator (^) directly on integers leverages the native CPU instruction, ensuring each arithmetic step is performed with minimal cost. The overall approach achieves optimal throughput for large inputs by reducing the per-query work to a fixed amount regardless of interval size.

written by openai gpt

ELI5 - Simplified Explanation

Imagine having a long line of numbered boxes. Sometimes a game asks to pick a start box and an end box and find a secret pattern hidden between them. To make this very fast, the computer first creates a special cheat sheet. This cheat sheet starts with a zero and then keeps track of a running secret code. Every time the computer looks at a new box, it combines the number in that box with the last secret code it found using a special logic trick that acts like a toggle switch.

When the game asks for a range, the computer looks at the cheat sheet instead of checking all the boxes one by one. By taking the secret code from the start point and the end point on the cheat sheet and combining them, the answer appears instantly. It is like having a shortcut that lets the computer skip all the hard work in the middle. The cheat sheet remembers everything that came before, so finding the answer for any range becomes as easy as snapping fingers together.

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 = 9 | μ = 8.48 | σ = 0.79

Complexity Analysis

Time: linear
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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ JS Java Python Go TS
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
qiyuangong C++
suxrobGM C#
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, TypeScript
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
qiyuangong C++
suxrobGM C#
varunu28 Java
30 links | 18 authors | 8 languages

Videos

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

Solved On The Same Day

5 solutions   January 9, 2024

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