#1829
Maximum XOR for Each Query
MediumArrayBit ManipulationPrefix SumBit ManipulationPrefix Sum
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)
Instead of checking every possible k, we can leverage the property of XOR and the maximum possible value we can achieve. The maximum XOR value for any prefix is 2^maximumBit - 1, and we can directly compute the result for each query based on the cumulative XOR.
⚙️
Algorithm
3 steps- 1Step 1: Initialize totalXor to 0 and create an empty result array.
- 2Step 2: Iterate through nums in reverse order, updating totalXor with each element.
- 3Step 3: For each query, calculate k as (2^maximumBit - 1) ^ totalXor and store it in the result array.
solution.py8 lines
1def maximizeXor(nums, maximumBit):
2 total_xor = 0
3 result = []
4 max_k = (1 << maximumBit) - 1
5 for num in reversed(nums):
6 total_xor ^= num
7 result.append(total_xor ^ max_k)
8 return result[::-1]ℹ
Complexity note: This is efficient because we only traverse the nums array once, calculating the cumulative XOR and the result in a single pass.
- 1The maximum possible XOR value is always 2^(maximumBit) - 1.
- 2Using cumulative XOR allows us to compute results efficiently without iterating through all possible k values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.