LeetCode 题解工作台
子数组异或查询
有一个正整数数组 arr ,现给你一个对应的查询数组 queries ,其中 queries[i] = [L i, R i ] 。 对于每个查询 i ,请你计算从 L i 到 R i 的 XOR 值(即 arr[L i ] xor arr[L i +1] xor ... xor arr[R i ] …
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 前缀和
答案摘要
我们可以用一个长度为 的前缀异或数组 来存储数组 的前缀异或结果,其中 $s[i] = s[i-1] \oplus \textit{arr}[i-1]$,即 表示 的前 个元素的异或结果。 那么对于一个查询 ,我们可以得到:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 前缀和 题型思路
题目描述
有一个正整数数组 arr,现给你一个对应的查询数组 queries,其中 queries[i] = [Li, Ri]。
对于每个查询 i,请你计算从 Li 到 Ri 的 XOR 值(即 arr[Li] xor arr[Li+1] xor ... xor arr[Ri])作为本次查询的结果。
并返回一个包含给定查询 queries 所有结果的数组。
示例 1:
输入:arr = [1,3,4,8], queries = [[0,1],[1,2],[0,3],[3,3]] 输出:[2,7,14,8] 解释: 数组中元素的二进制表示形式是: 1 = 0001 3 = 0011 4 = 0100 8 = 1000 查询的 XOR 值为: [0,1] = 1 xor 3 = 2 [1,2] = 3 xor 4 = 7 [0,3] = 1 xor 3 xor 4 xor 8 = 14 [3,3] = 8
示例 2:
输入:arr = [4,8,2,10], queries = [[2,3],[1,3],[0,0],[0,3]] 输出:[8,0,4,4]
提示:
1 <= arr.length <= 3 * 10^41 <= arr[i] <= 10^91 <= queries.length <= 3 * 10^4queries[i].length == 20 <= queries[i][0] <= queries[i][1] < arr.length
解题思路
方法一:前缀异或
我们可以用一个长度为 的前缀异或数组 来存储数组 的前缀异或结果,其中 ,即 表示 的前 个元素的异或结果。
那么对于一个查询 ,我们可以得到:
时间复杂度 ,空间复杂度 。其中 和 分别是数组 的长度和查询数组 的长度。
class Solution:
def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]:
s = list(accumulate(arr, xor, initial=0))
return [s[r + 1] ^ s[l] for l, r in queries]
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n + q), where n is array length and q is number of queries, because building the prefix array takes O(n) and each query is answered in O(1). Space complexity is O(n) for the prefix XOR array, but additional space for output is negligible. |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
Check if you recognize that XOR has an inverse property that allows prefix computations.
- question_mark
They might ask for an optimization beyond naive O(n*q) subarray calculation.
- question_mark
Expect a hint about building cumulative data structures, specifically prefix XOR, for constant-time queries.
常见陷阱
外企场景- error
Not initializing prefix array with zero leading to incorrect XOR for subarrays starting at index 0.
- error
Attempting to iterate over the subarray for each query, resulting in TLE for large inputs.
- error
Misunderstanding XOR properties, especially forgetting that x ^ x = 0 can simplify calculations.
进阶变体
外企场景- arrow_right_alt
Compute XOR for dynamic ranges where elements are updated between queries.
- arrow_right_alt
Use XOR queries on a 2D matrix instead of a 1D array, applying similar prefix ideas.
- arrow_right_alt
Determine the maximum XOR among all subarray ranges instead of specific queries.