![]() |
VOOZH | about |
Given arrays Arr[] and Queries[] of size N and an integer K such that (0 ≤ Arr[i], Queries[i] < 2K), the task is to form an array, where each element represents an integer such that XOR of all elements of array and element is maximum by updating Arr[i] with Queries[i] at each step (0 ≤ i ≤ N-1).
Examples:
Input: N = 4, Arr[] = {2, 3, 4, 7}, Queries[] = {1, 0, 3, 4}, K = 4
Output: {14, 13, 10, 9}
Explanation: The queries are answered as follows:
- 1st query: Arr[] = {2, 3, 4, 7}, After Updating Arr[] = {1, 3, 4, 7} then Choosing X = 14 since 1 XOR 3 XOR 4 XOR 7 XOR 14 = 15 which is the maximum.
- 2nd query: Arr[] = {1, 3, 4, 7}, After Updating Arr[] = {1, 0, 4, 7} then Choosing X = 13 since 1 XOR 0 XOR 4 XOR 7 XOR 13 = 15 which is the maximum.
- 3rd query: Arr[] = {1, 0, 4, 7}, After Updating Arr[[ = {1, 0, 3, 7} then Choosing X = 10 since 1 XOR 0 XOR 3 XOR 7 XOR 10 = 15 which is the maximum.
- 1st query: Arr[] = {1, 0, 3, 7}, After Updating Arr[] = {1, 0, 3, 4 ] then Choosing X = 9 since 1 XOR 0 XOR 3 XOR 4 XOR 9 = 15 which is the maximum.
Input: N = 3, Arr[] = {0, 1, 3}, Queries[] = {2, 2, 2}, K = 3
Output: {7, 4, 5}
Explanation: The queries are answered as follows :
- 1st query: Arr[] = {0, 1, 3}, After Updating Arr[] = {2, 1, 3} then Choosing X = 7 since 2 XOR 1 XOR 3 XOR 7 = 7 which is the maximum .
- 2nd query: Arr[] = {2, 1, 3}, After Updating Arr[] = {2, 2, 3} then Choosing X = 4 since 2 XOR 2 XOR 3 XOR 4 = 7 which is the maximum .
- 3rd query: Arr[] = {2, 2, 3}, After Updating Arr[] = {2, 2, 2} then Choosing X = 5 since 2 XOR 2 XOR 2 XOR 5 = 7 which is the maximum.
Approach: This problem can be solved with the following idea:
Calculate xor of the array Arr[] and let it be Q, We know the xor property that a xor b = c then a xor c = b or b xor c = a . We need xor to be maximum for every query so rhs will always be (2K - 1) then the equation becomes Q ^ X = (2K - 1) or X = Q ^ (2K - 1) .
Follow the steps to implement the idea:
Below is the implementation of the above algorithm :
14 13 10 9
Time Complexity: O(N)
Auxiliary Space: O(N)
Related Articles: