Queries for number of distinct elements in a subarray in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size n. And Q queries, each consisting of two elements l and r. Our task is to create a program to solve Queries for number of distinct elements in a subarray in C++.

Problem description − Here for each querry, we need to find the total number of distinct integers in the subarray starting from arr[l] to arr[r].

Let’s take an example to understand the problem,

Input

arr[] = {5, 6, 1, 6, 5, 2, 1}
Q = 2
{{1, 4}, {0, 6}}

Output

3
4

Explanation

For querry 1: l = 1 and r = 4, subarray[1...4] = {6, 1, 6, 5}, distinct element’s = 3.

For querry 2 − l = 0 and r = 6, subarray[0...6] = {5, 6, 1, 6, 5, 2, 1}, distinct element’s = 4.

Solution Approach

To solve the problem, we will use the set data structure, whose length will give the count of distinct elements of the array for the range given in the querry. For each querry, we will insert all elements of the range in the array to the set. All duplicate elements of the subarray will be discarded and only distinct elements will be stored, hence the size of the set will give the number of distinct elements.

Progam to illustrate the working of our solution,

Example

 Live Demo

#include<bits/stdc++.h>
using namespace std;

int solveQuery(int arr[], int l, int r) {

   set<int> distElements;
   for (int i = (r); i >= (l); i--)
   distElements.insert(arr[i]);
   return distElements.size();
}

int main() {

   int arr[] = {5, 6, 1, 6, 5, 2, 1};
   int n = sizeof(arr)/sizeof(arr[0]);
   int Q = 2;
   int query[Q][2] = {{1, 4}, {0,6}};
   for(int i = 0; i < Q; i++)
   cout<<"For Query "<<(i+1)<<": The number of distinct elements in subarray is "<<solveQuery(arr,    query[i][0], query[i][1])<<"\n";
   return 0;
}

Output

For Query 1: The number of distinct elements in subarray is 3
For Query 2: The number of distinct elements in subarray is 4
raja
Published on 06-Aug-2020 10:53:38
Advertisements