Maximum XOR Score Subarray Queries Problem
Description
LeetCode Problem 3277.
You are given an array nums of n integers, and a 2D integer array queries of size q, where queries[i] = [l_i, r_i].
For each query, you must find the maximum XOR score of any subarray of nums[l_i..r_i].
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 indicesiexcept 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.
Example 1:
Input: nums = [2,8,4,32,16,1], queries = [[0,2],[1,4],[0,5]]
Output: [12,60,60]
Explanation:
In the first query, nums[0..2] has 6 subarrays [2], [8], [4], [2, 8], [8, 4], and [2, 8, 4] each with a respective XOR score of 2, 8, 4, 10, 12, and 6. The answer for the query is 12, the largest of all XOR scores.
In the second query, the subarray of nums[1..4] with the largest XOR score is nums[1..4] with a score of 60.
In the third query, the subarray of nums[0..5] with the largest XOR score is nums[1..4] with a score of 60.
Example 2:
Input: nums = [0,7,3,2,8,5,1], queries = [[0,3],[1,5],[2,4],[2,6],[5,6]]
Output: [7,14,11,14,5]
Explanation:
Index nums[l_i..r_i] Maximum XOR Score Subarray Maximum Subarray XOR Score
0 [0, 7, 3, 2] [7] 7
1 [7, 3, 2, 8, 5] [7, 3, 2, 8] 14
2 [3, 2, 8] [3, 2, 8] 11
3 [3, 2, 8, 5, 1] [2, 8, 5, 1] 14
4 [5, 1] [5] 5
Constraints:
1 <= n == nums.length <= 20000 <= nums[i] <= 2^31 - 11 <= q == queries.length <= 10^5queries[i].length == 2queries[i] = [l_i, r_i]0 <= l_i <= r_i <= n - 1
Solution
Approach: Interval Dynamic Programming
The XOR score of a subarray reduces to XOR-ing adjacent pairs repeatedly. Let f[i][j] be the score of nums[i..j]: then f[i][j] = f[i][j-1] ^ f[i+1][j], with f[i][i] = nums[i].
Let g[i][j] be the maximum score over all subarrays inside nums[i..j]: g[i][j] = max(f[i][j], g[i][j-1], g[i+1][j]). Fill both tables for i from right to left, then answer each query [l, r] with g[l][r].
Complexity: O(n2 + q) time and O(n2) space.
class Solution:
def maximumSubarrayXor(
self, nums: List[int], queries: List[List[int]]
) -> List[int]:
n = len(nums)
f = [[0] * n for _ in range(n)]
g = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
f[i][i] = g[i][i] = nums[i]
for j in range(i + 1, n):
f[i][j] = f[i][j - 1] ^ f[i + 1][j]
g[i][j] = max(f[i][j], g[i][j - 1], g[i + 1][j])
return [g[l][r] for l, r in queries]