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
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.
Another solution is to store xor in all possible ranges but there are O(n^2) possible ranges hence with n ~ 10^5 it wil exceed space complexity, hence without considering time complexity, we can state this solution will not work.
Solution 3 (Segment Tree)
Prerequesite : 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 contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Segment Tree | (XOR of a given range )
- Segment Tree | Set 1 (Sum of given range)
- Segment Tree | Set 2 (Range Minimum Query)
- Iterative Segment Tree (Range Minimum Query)
- Segment Tree | Set 2 (Range Maximum Query with Node Update)
- Iterative Segment Tree (Range Maximum Query with Node Update)
- Overview of Data Structures | Set 3 (Graph, Trie, Segment Tree and Suffix Tree)
- Cartesian tree from inorder traversal | Segment Tree
- Two equal sum segment range queries
- Segment Trees | (Product of given Range Modulo m)
- LIS using Segment Tree
- Reconstructing Segment Tree
- Two Dimensional Segment Tree | Sub-Matrix Sum
- Persistent Segment Tree | Set 1 (Introduction)
- Lazy Propagation in Segment Tree