Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Queries to check whether all the elements in the given range occurs even number of times

  • Last Updated : 12 Nov, 2021

Given an array arr[] containing N integers and there are Q queries where each query consists of a range [L, R]. The task is to find whether all the elements from the given index range have even frequency or not.
Examples: 
 

Input: arr[] = {1, 1, 2, 2, 1}, Q[][] = {{1, 5}, {1, 4}, {3, 4}} 
Output: 
No 
Yes 
Yes
Input: arr[] = {100, 100, 200, 100}, Q[][] = {{1, 4}, {1, 2}} 
Output: 
No 
Yes 
 

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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

 



Naive approach: A simple approach will be to iterate from the index range [L, R] for each of the query and count the frequency of each element in that range and check that every element is occurring even number of times or not. The worst case time complexity of this approach will be O(Q * N) where Q is the number of queries and N is the number of elements in the array.
Efficient approach: Since XOR of two equal number is 0 i.e. if all the elements of the array appears even number of times then the XOR of the complete array will be 0. The same can be said about the elements in the given range [L, R]. Now, to check if the XOR of all the elements in the given range is 0 or not, a prefix XOR array can be created where preXor[i] will store the XOR of the elements arr[0…i]. And the XOR of the elements arr[i…j] can be easily calculated as preXor[j] ^ preXor[i – 1].
Below is the implementation of the above approach: 
 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to perform the given queries
void performQueries(vector<int>& A,
                    vector<pair<int, int> >& q)
{
 
    int n = (int)A.size();
 
    // Making array 1-indexed
    A.insert(A.begin(), 0);
 
    // To store the cumulative xor
    vector<int> pref_xor(n + 1, 0);
 
    // Taking cumulative Xor
    for (int i = 1; i <= n; ++i) {
        pref_xor[i]
            = pref_xor[i - 1] ^ A[i];
    }
 
    // Iterating over the queries
    for (auto i : q) {
        int L = i.first, R = i.second;
        if (L > R)
            swap(L, R);
 
        // If both indices are different and xor
        // in the range [L, R] is 0
        if (L != R and pref_xor[R] == pref_xor[L - 1])
            cout << "Yes\n";
        else
            cout << "No\n";
    }
}
 
// Driver code
int main()
{
 
    vector<int> Arr = { 1, 1, 2, 2, 1 };
 
    vector<pair<int, int> > q = {
        { 1, 5 },
        { 1, 4 },
        { 3, 4 }
 
    };
 
    performQueries(Arr, q);
 
    return 0;
}

Java




// Java implementation of the approach
import java.util.*;
     
class GFG
{
static class pair
{
    int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to perform the given queries
static void performQueries(int []A,
                           pair[] q)
{
    int n = A.length;
 
    // To store the cumulative xor
    int []pref_xor = new int[n + 1];
 
    // Taking cumulative Xor
    for (int i = 1; i <=n; ++i)
    {
        pref_xor[i] = pref_xor[i - 1] ^
                             A[i - 1];
    }
 
    // Iterating over the queries
    for (pair i : q)
    {
        int L = i.first, R = i.second;
        if (L > R)
        {
            int temp = L;
            L = R;
            R = temp;
        }
         
        // If both indices are different and xor
        // in the range [L, R] is 0
        if (L != R && pref_xor[R] == pref_xor[L - 1])
            System.out.println("Yes");
    else
        System.out.println("No");
    }
}
 
// Driver code
static public void main (String []arg)
{
    int []Arr = { 1, 1, 2, 2, 1 };
    pair[] q = { new pair(1, 5 ),
                 new pair(1, 4 ),
                 new pair(3, 4 ) };
 
    performQueries(Arr, q);
}
}
 
// This code is contributed by 29AjayKumar

Python3




# Python3 implementation of the approach
 
# Function to perform the given queries
def performQueries(A, q):
 
    n = len(A)
     
    # To store the cumulative xor
    pref_xor = [0 for i in range(n + 1)]
 
    # Taking cumulative Xor
    for i in range(1, n + 1):
        pref_xor[i] = pref_xor[i - 1] ^ A[i - 1]
 
    # Iterating over the queries
    for i in q:
        L = i[0]
        R = i[1]
        if (L > R):
            L, R = R, L
 
        # If both indices are different and
        # xor in the range [L, R] is 0
        if (L != R and
            pref_xor[R] == pref_xor[L - 1]):
            print("Yes")
        else:
            print("No")
 
# Driver code
Arr = [1, 1, 2, 2, 1]
 
q = [[ 1, 5 ],
     [ 1, 4 ],
     [ 3, 4 ]]
 
performQueries(Arr, q);
 
# This code is contributed by Mohit Kumar

C#




// C# implementation of the approach
using System;
     
class GFG
{
public class pair
{
    public int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
// Function to perform the given queries
static void performQueries(int []A,
                           pair[] q)
{
    int n = A.Length;
 
    // To store the cumulative xor
    int []pref_xor = new int[n + 1];
 
    // Taking cumulative Xor
    for (int i = 1; i <= n; ++i)
    {
        pref_xor[i] = pref_xor[i - 1] ^
                             A[i - 1];
    }
 
    // Iterating over the queries
    foreach (pair k in q)
    {
        int L = k.first, R = k.second;
        if (L > R)
        {
            int temp = L;
            L = R;
            R = temp;
        }
         
        // If both indices are different and xor
        // in the range [L, R] is 0
        if (L != R && pref_xor[R] == pref_xor[L - 1])
            Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
    }
}
 
// Driver code
static public void Main (String []arg)
{
    int []Arr = { 1, 1, 2, 2, 1 };
    pair[] q = {new pair(1, 5 ),
                new pair(1, 4 ),
                new pair(3, 4 )};
 
    performQueries(Arr, q);
}
}
     
// This code is contributed by Rajput-Ji

Javascript




<script>
// Javascript implementation of the approach
 
// Function to perform the given queries
function performQueries(A, q) {
 
    let n = A.length
 
    // To store the cumulative xor
    let pref_xor = new Array(n + 1).fill(0)
 
    // Taking cumulative Xor
    for (let i = 1; i < n + 1; i++) {
        pref_xor[i] = pref_xor[i - 1] ^ A[i - 1]
    }
 
    // Iterating over the queries
    for (let i in q) {
        let L = i[0]
        let R = i[1];
        if (L > R) {
            let temp = R;
            R = L;
            L = temp
        }
 
        // If both indices are different and
        // xor in the range [L, R] is 0
        if ((L != R) && (pref_xor[R] == pref_xor[L - 1]))
            document.write("No<br>")
        else
            document.write("Yes<br>")
    }
}
// Driver code
let Arr = [1, 1, 2, 2, 1]
 
let q = [[1, 5],
[1, 4],
[3, 4]]
 
performQueries(Arr, q);
 
 
// This code is contributed by gfgking
</script>
Output: 
No
Yes
Yes

 

Time Complexity: O(N)

Auxiliary Space: O(N)
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :