VOOZH about

URL: https://www.geeksforgeeks.org/dsa/xor-numbers-appeared-even-number-times-given-range/

⇱ XOR of numbers that appeared even number of times in given Range - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

XOR of numbers that appeared even number of times in given Range

Last Updated : 11 Jul, 2025

Given an array of numbers of size N and Q queries. Each query or a range can be represented by L (LeftIndex) and R(RightIndex). Find the XOR-sum of the numbers that appeared even number of times in the given range.

Prerequisite : Queries for number of distinct numbers in given range. | Segment Tree for range query

Examples : 

Input : arr[] = { 1, 2, 1, 3, 3, 2, 3 }
Q = 5
L = 3, R = 6
L = 3, R = 4
L = 0, R = 2
L = 0, R = 6
L = 0, R = 4
Output : 0
3
1
3
2


Explanation of above example: 

In Query 1, there are no numbers which appeared even number of times. 
Hence the XOR-sum is 0. 
In Query 2, {3} appeared even number of times. XOR-sum is 3. 
In Query 3, {1} appeared even number of times. XOR-sum is 1. 
In Query 4, {1, 2} appeared even number of times. XOR-sum is 1 xor 2 = 3. 
In Query 5, {1, 3} appeared even number of times. XOR-sum is 1 xor 3 = 2.

Segment Trees or Binary Indexed Trees can be used to solve this problem efficiently.

Approach : 

Firstly, it is easy to note that the answer for the query is the XOR-sum of all elements in the query range xor-ed with XOR-sum of distinct elements in the query range (since taking XOR of an element with itself results into a null value). Find the XOR-sum of all numbers in query range using prefix XOR-sums. 

To find the XOR-sum of distinct elements in range :Number of distinct elements in a subarray of given range
Now, returning back to our main problem, just change the assignment BIT[i] = 1 to BIT[i] = arri and count the XOR-sum instead of sum. 

Below is the implementation using Binary Indexed Trees:


Output
0
3
1
3
2

Complexity Analysis:

  • Time Complexity:O(Q * Log(N)), where N is the size of array, Q is the total number of queries.
  • Space complexity: O(N) where N is size of array.

Approach : Using Mo's Algorithm

  • Sort the queries based on their left endpoints.
  • Maintain a data structure to track the count of numbers in the current window.
  • Process the queries one by one and update the count of numbers in the window accordingly, calculating the XOR-sum as needed.

Below is the implementation :

Output :

0
3
1
3
2

Complexity analysis :

Time Complexity: O((N+Q) N1/2) where N is the size of the array & Q is the number of queries.

Space complexity: O(N+Q)

Comment