#3277
Maximum XOR Score Subarray Queries
HardArrayDynamic ProgrammingPrefix SumDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
By precomputing the XOR for all subarrays, we can efficiently answer each query in constant time. This takes advantage of the properties of XOR and cumulative results.
⚙️
Algorithm
3 steps- 1Step 1: Create an array 'prefixXor' where prefixXor[i] is the XOR of nums[0] to nums[i].
- 2Step 2: For each query, calculate the XOR of the subarray using the prefixXor array.
- 3Step 3: Track the maximum XOR score for all subarrays within the specified range.
solution.py17 lines
1def maxXorSubarray(nums, queries):
2 n = len(nums)
3 prefixXor = [0] * n
4 prefixXor[0] = nums[0]
5 for i in range(1, n):
6 prefixXor[i] = prefixXor[i - 1] ^ nums[i]
7 results = []
8 for l, r in queries:
9 max_xor = 0
10 for i in range(l, r + 1):
11 for j in range(i, r + 1):
12 current_xor = prefixXor[j]
13 if i > 0:
14 current_xor ^= prefixXor[i - 1]
15 max_xor = max(max_xor, current_xor)
16 results.append(max_xor)
17 return resultsℹ
Complexity note: The time complexity is O(n) for preprocessing the prefix XOR array, and each query can be answered in O(1) time, making it efficient overall.
- 1Understanding XOR properties can lead to efficient solutions.
- 2Precomputing results can save time during query processing.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.