I recently came across this question. Given an array of integers we have to find the bitwise XOR of bitwise AND of all the subarrays of size atmost K.
INPUT
N = 5
A = [5,7,8,2,6]
K = 3
OUTPUT
9
Explanation: The possible bitwise AND of subarrays having size atmost 3 are -
[5,5] = 6
[4,4] = 2 , [4,5] = 2
[3,3] = 8 , [3,4] = 0 , [3,5] = 0
[2,2] = 7 , [2,3] = 0 , [2,4] = 0
[1,1] = 5 , [1,2] = 5 , [1,3] = 0
The XOR of all ANDS = 6^2^2^8^0^0^7^0^0^5^5^0 = 9.
Given N <= 1e5 , K <= N , A[i] <= 1e5. Can someone guide on how to solve this problem.








Link.
Focus on ith bit of all the numbers. Just write down the ith bit of all numbers in order as they are given in array. It will look something like: {0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0 }. How many times 1 appear in the ith bit in all the ANDS of all subarrays? (I mean if the AND of all subarrays are-> {A1, A2, A3,....AK} , K is no of subarrays, then what is the frequency of 1 in the ith bit of all those numbers?) Every 1 (suppose at jth index) appearing in array contributes (C*(C+1))/2 to the frequency of 1, where C=min(K,L), here L is max length of the contiguous 1's starting from jth index. If the total frequency of 1 is even, then ith bit of the XOR i.e A1^A2^A3...^AK is 0, otherwise it's 1.
Solution is of O(N*logN).