Queries for number of distinct integers in Suffix in C++


In this problem, we are given an array of N integers. There are Q queries, each containing an integer value m. Our task to create a program to solve Queries for number of distinct integers in Suffix in C++.

Problem description − Here, we will need to find the total number of distinct integers that are present in the subarray from the index (m-1) to (N-1). Where m is the value in each query.

Let’s take an example to understand the problem −

Input

array = {2, 6, 1, 2, 7, 6}
Q = 2 , queries = {1, 5}

Output

4 2

Explanation

For m = 1, we need to find the number of the distinct elements from index 0 to N, which is 4.

For m = 5, we need to find the number of distinct elements from index 4 to N, which is 2.

Solution Approach

The solution to this problem is simple as depicted in the example. We need to simply count the number of unique or distinct elements in the array. If we are considering the data structure as an array, it seems difficult. But if we consider using other data structure the solution will be easy.

So, for solving the problem, we will be using a set in C++ which is available in the STL library. So, for each query, we will insert the elements from the index (m-1) to (n-1) in the set. And the length of the set gives the number of distinct elements for the query.

Program to illustrate our solution,

Example

 Live Demo

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

int findDistinctInt(int arr[], int N, int m) {

   set<int> distValues;
   for (int i = (N-1); i >= (m-1); i--) {
      distValues.insert(arr[i]);
   }
   return distValues.size();
}

int main() {

   int arr[] = { 2, 6, 1, 2, 7, 6 };
   int N = sizeof(arr) / sizeof(arr[0]);
   int Q = 2;
   int query[Q] = { 1, 5 };

   for(int i = 0; i < Q; i++)
   cout<<"For query "<<(i+1)<<": The number of distinct integer in Suffix is "<<findDistinctInt(arr,    N, query[i])<<endl;

   return 0;
}

Output

For Query 1: The number of distinct integer in Suffix is 4
For Query 2: The number of distinct integer in Suffix is 2

Updated on: 09-Sep-2020

58 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements