VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-xor-of-numbers-from-the-range-l-r/

⇱ XOR of Number Range [L, R] - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

XOR of Number Range [L, R]

Last Updated : 3 May, 2026

Given two integers L and R, the task is to find the XOR of elements of the range [L, R]
Examples:

Input: L = 4, R = 8 
Output:
Explanation: 4 ^ 5 ^ 6 ^ 7 ^ 8 = 8

Input: L = 2, R = 4 
Output: 5
Explanation: 2 ^ 3 ^ 4 = 5  

[Naive Approach] Simple Loop - O(n) Time and O(1) Space

Initialize answer as zero, Traverse all numbers from L to R and perform XOR of the numbers one by one with the answer.


Output
8

[Efficient Approach] Using XOR Pattern - O(1) Time and O(1) Space

Use the repeating XOR pattern from 1 to n and compute the range XOR as: XOR(L to R) = XOR(1 to R) ^ XOR(1 to L-1).

How does this work? We mainly get the elements from 1 to L-1 appeared twice in x1 ^ x2 and if we do XOR of an element with itself, we get 0 and if we do XOR of 0 with an element x, we get x.

How do we find XOR of 1 to n Find the remainder of n by moduling it with 4. 

  • If rem = 0, then XOR will be same as n. 
  • If rem = 1, then XOR will be 1. 
  • If rem = 2, then XOR will be n+1. 
  • If rem = 3 ,then XOR will be 0.

Please refer XOR of 1 to n for working of this.


Output
8
Comment
Article Tags:
Article Tags: