Problem Description
Given a sorted array of non-negative integers nums and an integer maximumBit, you need to answer n queries. Each query consists of finding a non-negative integer k (with k < 2^(maximumBit)) such that when you XOR k with the XOR of all elements currently in nums, the result is maximized. After answering a query, the last element of nums is removed. Return an array answer where answer[i] is the result to the i-th query.
Key Insights
- Compute the XOR of the entire array once.
- A number k that maximizes (XOR sum of nums) XOR k is simply the bitwise complement of the XOR sum within the range [0, 2^(maximumBit)-1].
- The bitmask (1 << maximumBit) - 1 represents the maximum value with maximumBit bits all set to 1.
- After each query, update the cumulative XOR by removing the contribution of the removed (last) element.
- Process the queries in order by simulating the removal from the end of the array.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements in nums, as we calculate the initial XOR then process each element once. Space Complexity: O(n) for storing the answer array (ignoring the space used for input).
Solution
We start by computing the cumulative XOR of all the numbers in nums. The maximum value that can be achieved by XORing with a number k (where k < 2^(maximumBit)) is obtained by flipping all the bits of the cumulative XOR within the range defined by maximumBit. This is done by XORing the cumulative XOR with the mask (which is (1 << maximumBit) - 1). For each query, we store the result and then remove the last element from nums by updating the cumulative XOR (using XOR with that element) before moving to the next query. Note that the queries are answered in the order of removal from the end of the array, which directly produces the answer sequence.