Problem
You are given an array nums
of n
integers, and a 2D integer array
queries
of size q
, where queries[i] = [li, ri]
.
For each query, you must find the maximum XOR score of any subarray of
nums[li..ri]
.
The XOR score of an array a
is found by repeatedly applying the following operations on a
so that only one element remains, that is the
score :
- Simultaneously replace
a[i]
witha[i] XOR a[i + 1]
for all indicesi
except the last one. - Remove the last element of
a
.
Return an array answer
of size q
where answer[i]
is the answer to query
i
.
Examples
Example 1
|
|
Example 2
|
|
Constraints
1 <= n == nums.length <= 2000
0 <= nums[i] <= 2^31 - 1
1 <= q == queries.length <= 10^5
queries[i].length == 2
queries[i] = [li, ri]
0 <= li <= ri <= n - 1
Solution
Method 1 – Prefix XOR and Brute Force
Intuition
The XOR score of a subarray is the XOR of all its elements. For each query, we need the maximum XOR of any subarray within the given range. We can use prefix XORs to compute the XOR of any subarray efficiently, and then check all possible subarrays in the range.
Approach
- Precompute prefix XORs for the array.
- For each query
[l, r]
, iterate over all possible subarrays innums[l..r]
. - For each subarray, compute its XOR using prefix XORs.
- Track the maximum XOR score for each query.
- Return the results for all queries.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(q * n^2)
, for each query, we check all subarrays in the range. - 🧺 Space complexity:
O(n)
, for prefix XORs.