Queries for number of distinct integers in Suffix

Given an array of N elements and Q queries, where each query contains an integer K. For each query, the task is to find the number of distinct integers in the suffix from Kth element to Nth element.

Examples:

Input :
N=5, Q=3
arr[] = {2, 4, 6, 10, 2}
1
3
2
Output :
4
3
4


Approach:
The problem can be solved by precomputing the solution for all index from N-1 to 0. The idea is to use an unordered_set in C++ as set doesnot allows duplicate elements.

Traverse the array from end and add the current element into a set and the answer for the current index would be the size of the set. So, store the size of set at current index in an auxiliary array say suffixCount.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find distinct
// elements in suffix
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to answer queries for distinct
// count in Suffix
void printQueries(int n, int a[], int q, int qry[])
{
    // Set to keep the distinct elements
    unordered_set<int> occ;
  
    int suffixCount[n + 1];
  
    // Precompute the answer for each suffix
    for (int i = n - 1; i >= 0; i--) {
        occ.insert(a[i]);
        suffixCount[i + 1] = occ.size();
    }
  
    // Print the precomputed answers
    for (int i = 0; i < q; i++)
        cout << suffixCount[qry[i]] << endl;
}
  
// Driver Code
int main()
{
    int n = 5, q = 3;
    int a[n] = { 2, 4, 6, 10, 2 };
    int qry[q] = { 1, 3, 2 };
  
    printQueries(n, a, q, qry);
  
    return 0;
}

chevron_right


Python3

# Python3 program to find distinct
# elements in suffix

# Function to answer queries for distinct
# count in Suffix
def printQueries(n, a, q, qry):

# Set to keep the distinct elements
occ = dict()

suffixCount = [0 for i in range(n + 1)]

# Precompute the answer for each suffix
for i in range(n – 1, -1, -1):
occ[a[i]] = 1
suffixCount[i + 1] = len(occ)

# Pr the precomputed answers
for i in range(q):
print(suffixCount[qry[i]])

# Driver Code
n = 5
q = 3
a = [2, 4, 6, 10, 2]
qry = [1, 3, 2]

printQueries(n, a, q, qry)

# This code is contributed by Mohit Kumar 29

Output:

4
3
4

Time Complexity: O(N)
Auxiliary Space: O(N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : mohit kumar 29