Given two integers L and R, the task is to find the XOR of elements of the range [L, R].
Input: L = 4, R = 8
4 ^ 5 ^ 6 ^ 7 ^ 8 = 8
Input: L = 3, R = 7
Naive Approach: Intilialize answer as zero, Traverse all numbers from L to R and perform XOR of the numbers one by one with the answer. This would take O(N) time.
Efficient Approach: By following the approach discussed here, we can find the XOR of elements from the range [1, N] in O(1) time.
Using this approach, we have to find xor of elements from the range [1, L – 1] and from the range [1, R] and then xor the respective answers again to get the xor of the elements from the range [L, R]. This is because every element from the range [1, L – 1] will get XORed twice in the result resulting in a 0 which when XORed with the elements of the range [L, R] will give the result.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Find XOR of two number without using XOR operator
- Given a set, find XOR of the XOR's of all subsets.
- Number of ways to obtain each numbers in range [1, b+c] by adding any two numbers in range [a, b] and [b, c]
- Check whether XOR of all numbers in a given range is even or odd
- Choose X such that (A xor X) + (B xor X) is minimized
- Range Queries to Find number of sub-arrays with a given xor
- Find the XOR of the elements in the given range [L, R] with the value K for a given set of queries
- Absolute difference between the XOR of Non-Prime numbers and Prime numbers of an Array
- Maximum XOR value of a pair from a range
- Segment Tree | Set 3 (XOR of given range)
- Queries on XOR of greatest odd divisor of the range
- Range Query on array whose each element is XOR of index value and previous element
- Segment Tree | (XOR of a given range )
- XOR of a subarray (range of elements)
- Number whose sum of XOR with given array range is maximum
- Value in a given range with maximum XOR
- XOR of all the elements in the given range [L, R]
- XOR in a range of a binary array
- Range Update Queries to XOR with 1 in a Binary Array.
- XOR of elements in a given range with updates using Fenwick Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.