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


In this problem, we are given an array arr[] of n integer values. And Q queries each having an integer k. Our task is to create a program to solve the Queries for number of distinct integers in Suffix.

Problem Description − We need to solve queries for distinct integers in suffix. For each query we need to find the number of unique elements from k to n i.e. count unique elements from arr[k] to arr[n].

The array taken is 1 indexed.

Let’s take an example to understand the problem,

Input

arr[ ] = {5, 1, 2, 1, 6 , 5}, n = 6, Q = 3, query = {1, 3, 4}

Output

4 4 3

Explanation

For Query 1: k = 1, N = 6, Count of elements from arr[1] to arr[6]. Count = 4.
For Query 2: k = 3, N = 6, Count of elements from arr[3] to arr[6]. Count = 4
For Query 3: k = 4, N = 6, Count of elements from arr[4] to arr[6]. Count = 3

Solution Approach

A simple solution to the problem to solve each query by starting from index k to n. And count all unique elements of the array and return the count of each query.

Effective solution

An effective solution to the problem is using a precomputed data structure that stores the unique count for index from (n-1) to 0. It is done by using a unordered set to eliminate addition of duplicate elements. We can even use an auxiliary array too, for occurrence count.

We will add elements of the array to our data structure starting from last till the kth element and then find the count of elements in the data structure (in case of array value at kth index).

Program to illustrate the working of our solution,

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void solveQueries_DistInt(int n, int arr[], int Q, int queries[]) {
   unordered_set<int> uniqueInts;
   int distIntCount[n + 1];
   for (int i = n - 1; i >= 0; i--) {
      uniqueInts.insert(arr[i]);
      distIntCount[i + 1] = uniqueInts.size();
   }
   for (int i = 0; i < Q; i++)
   cout<<"For Query "<<(i+1)<<": the number of distinct integers in Suffix is "<<distIntCount[queries[i]]<<endl;
}
int main() {
   int n = 6, Q = 3;
   int arr[n] = {5, 1, 2, 1, 6, 5};
   int queries[Q] = {1, 3, 4};
   solveQueries_DistInt(n, arr, Q, queries);
   return 0;
}

Output

For Query 1: the number of distinct integers in Suffix is 4
For Query 2: the number of distinct integers in Suffix is 4
For Query 3: the number of distinct integers in Suffix is 3

Updated on: 22-Dec-2020

177 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements