Given a sequence of integers, d[1],d[2],…,d[N] (1<=N<=100,000), find the consecutive subsequnce such that the bitwise XOR between the subsequence has the maximum value. (0<=d[i]<(2^21))
Solution
At first, we need to know a property of xor (exclusive or) operation:
If a xor b equals c, then the xor of any two of a,b,c, equals the other one.
Let xr[i] be the xor of d[1],d[2],…,d[i], 1<=i<=N. Suppose xr[0]=0, then the xor of the sequence d[i],…,d[j] equals xr[i-1] xor xr[j]. Apparently, the maximam value is max{xr[i] xor xr[j]}, where 0<=i<j<=N.
For each j, 1<=j<=N, we only need to find an i (0<=i<j), such that xr[i] xor xr[j] is maximal. That is, we need to find a xr[i] which is most different from x[j]. Since N can be as large as 100,000, we need to use an algorithm faster than O(N^2).
Note that d[i] is in the range from 0 to (2^21)-1, so xr[i] is also in this range, and its binary representation has at most 21 digits.
Limited length and limited options for each digit lead me to think about Trie, which can greatly reduce time complexity. So I used Trie to keep values of the array xr.