Segment Tree | Set 3 (XOR of given range)
We have an array arr[0 . . . n-1]. There are two type of queries
- Find the XOR of elements from index l to r where 0 <= l <= r <= n-1
- Change value of a specified element of the array to a new value x. We need to do arr[i] = x where 0 <= i <= n-1.
There will be total of q queries.
n <= 10^5, q <= 10^5
Solution 1: A simple solution is to run a loop from l to r and calculate xor of elements in given range. To update a value, simply do arr[i] = x. The first operation takes O(n) time and second operation takes O(1) time. Worst case time complexity is O(n*q) for q queries
which will take huge time for n ~ 10^5 and q ~ 10^5. Hence this solution will exceed time limit.
Solution 2: Another solution is to store xor in all possible ranges but there are O(n^2) possible ranges hence with n ~ 10^5 it will exceed space complexity, hence without considering time complexity, we can state this solution will not work.
Solution 3 (Segment Tree):
Prerequisite : Segment Tree
We build a segment tree of given array such that array elements are at leaves and internal nodes store XOR of leaves covered under them.
Xor of values in given range = 1 Updated xor of values in given range = 8
Time and Space Complexity:
Time Complexity for tree construction is O(n).
There are total 2n-1 nodes, and value of every node is calculated only once in tree construction.
Time complexity to query is O(log n).
The time complexity of update is also O(log n).
Total time Complexity is : O(n) for construction + O(log n) for each query = O(n) + O(n * log n) = O(n * log n)
Time Complexity: O(n * log n)
Auxiliary Space: O(n)
This article is contributed by Pratik Chhajer. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.