Finding subarray whose xor is 0

谁都会走 提交于 2019-12-08 13:05:42

问题


I'm stuck at one problem i.e. to find a subarray whose xor is 0. I read somewhere that this can be done using TRIE data structure but I want the starting and ending indices of the array.

For example, consider an array

a = [3, 6, 13, 8 15]

The subarray from 0 to 3 i.e. [3, 6, 13, 8] has xor equal to 0. (3 xor 6 xor 13 xor 8 = 0) I'm in search for an algorithm than can find those indices ([0, 3] in this case).

Detailed answer would be very helpful.

Update I tried the brute Force approach find checking xor for all pairs of [i, j]. This gives TLE since the no. of elements in the array could be upto 10^5

The I tried a solution mentioned here but this doesn't give indices.

I'm looking for an algorithm with O(nLogn) or possibly O(n) complexity.


回答1:


This solution take O(n) complexity also. Take the benefit of unordered_map.

vector<int> a = {3,6,13,8,15};
unordered_map<int, int> hashMap;
int number_of_elements = a.size();
hashMap[0] = -1;
int xor_sum = 0;
for(int i = 0; i < number_of_elements; i++) {
    xor_sum ^= a[i];
    if(hashMap.find(xorSum) != hashMap.end()) {
        cout << hashMap[xorSum] + 1 << " " << i << endl;
        break;
    }
    hashMap[xor_sum] = i;
}


来源:https://stackoverflow.com/questions/57344230/finding-subarray-whose-xor-is-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!