Queries for number of distinct integers in Suffix
Last Updated :
16 Nov, 2022
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 does not allow 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++
// 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;
}
Java
// Java program to find distinct
// elements in suffix
import java.util.*;
class GFG
{
// Function to answer queries for distinct
// count in Suffix
static void printQueries(int n, int a[], int q, int qry[])
{
// Set to keep the distinct elements
HashSet<Integer> occ = new HashSet<>();
int []suffixCount = new int[n + 1];
// Precompute the answer for each suffix
for (int i = n - 1; i >= 0; i--)
{
occ.add(a[i]);
suffixCount[i + 1] = occ.size();
}
// Print the precomputed answers
for (int i = 0; i < q; i++)
System.out.println(suffixCount[qry[i]]);
}
// Driver Code
public static void main(String args[])
{
int n = 5, q = 3;
int a[] = { 2, 4, 6, 10, 2 };
int qry[] = { 1, 3, 2 };
printQueries(n, a, q, qry);
}
}
/* This code contributed by PrinciRaj1992 */
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)
# Print 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
C#
// C# program to find distinct
// elements in suffix
using System;
using System.Collections.Generic;
public class GFG
{
// Function to answer queries for distinct
// count in Suffix
static void printQueries(int n, int []a, int q, int []qry)
{
// Set to keep the distinct elements
HashSet<int> occ = new HashSet<int>();
int []suffixCount = new int[n + 1];
// Precompute the answer for each suffix
for (int i = n - 1; i >= 0; i--)
{
occ.Add(a[i]);
suffixCount[i + 1] = occ.Count;
}
// Print the precomputed answers
for (int i = 0; i < q; i++)
Console.WriteLine(suffixCount[qry[i]]);
}
// Driver Code
public static void Main(String []args)
{
int n = 5, q = 3;
int []a = { 2, 4, 6, 10, 2 };
int []qry = { 1, 3, 2 };
printQueries(n, a, q, qry);
}
}
// This code is contributed by Princi Singh
PHP
<?php
// PHP program to find distinct
// elements in suffix
// Function to answer queries for distinct
// count in Suffix
function printQueries($n, $a, $q, $qry)
{
// Set to keep the distinct elements
$occ = array();
$suffixCount = array_fill(0, $n + 1, 0);
// Precompute the answer for each suffix
for ($i = $n - 1; $i >= 0; $i--)
{
array_push($occ, $a[$i]);
# give array of distinct element
$occ = array_unique($occ);
$suffixCount[$i + 1] = sizeof($occ);
}
// Print the precomputed answers
for ($i = 0; $i < $q; $i++)
echo $suffixCount[$qry[$i]], "\n";
}
// Driver Code
$n = 5;
$q = 3;
$a = array(2, 4, 6, 10, 2);
$qry = array(1, 3, 2);
printQueries($n, $a, $q, $qry);
// This code is contributed by Ryuga
?>
JavaScript
<script>
// JavaScript program to find distinct
// elements in suffix
// Function to answer queries for distinct
// count in Suffix
function printQueries(n,a,q,qry)
{
// Set to keep the distinct elements
let occ = new Set();
let suffixCount = new Array(n + 1);
// Precompute the answer for each suffix
for (let i = n - 1; i >= 0; i--)
{
occ.add(a[i]);
suffixCount[i + 1] = occ.size;
}
// Print the precomputed answers
for (let i = 0; i < q; i++)
document.write(suffixCount[qry[i]]+"<br>");
}
// Driver Code
let n = 5, q = 3;
let a=[2, 4, 6, 10, 2];
let qry=[ 1, 3, 2 ];
printQueries(n, a, q, qry);
// This code is contributed by patel2127
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach without STL: Since queries need to be addressed, precomputation needs to be done. Otherwise, a simple traversal over the suffix would have sufficed.
An auxiliary array aux[] is maintained from the right side of the array. An array mark[] stores whether an element has occurred or not in the suffix traversed yet. If the element has not occurred, then update aux[i] = aux[i+1] + 1. Otherwise aux[i] = aux[i+1].
Answer for every query would be aux[q[i]].
Below is the implementation of the above approach.
C++
// C++ implementation of the above approach.
#include <bits/stdc++.h>
#define MAX 100002
using namespace std;
// Function to print no of unique elements
// in specified suffix for each query.
void printUniqueElementsInSuffix(const int* arr,
int n, const int* q, int m)
{
// aux[i] stores no of unique elements in arr[i..n]
int aux[MAX];
// mark[i] = 1 if i has occurred in the suffix at least once.
int mark[MAX];
memset(mark, 0, sizeof(mark));
// Initialization for the last element.
aux[n - 1] = 1;
mark[arr[n - 1]] = 1;
for (int i = n - 2; i >= 0; i--) {
if (mark[arr[i]] == 0) {
aux[i] = aux[i + 1] + 1;
mark[arr[i]] = 1;
}
else {
aux[i] = aux[i + 1];
}
}
for (int i = 0; i < m; i++) {
cout << aux[q[i] - 1] << "\n";
}
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 4, 1, 2, 3, 4, 10000, 999 };
int n = sizeof(arr) / sizeof(arr[0]);
int q[] = { 1, 3, 6 };
int m = sizeof(q) / sizeof(q[0]);
printUniqueElementsInSuffix(arr, n, q, m);
return 0;
}
Java
// Java implementation of the above approach.
class GFG
{
static int MAX = 100002;
// Function to print no of unique elements
// in specified suffix for each query.
static void printUniqueElementsInSuffix(int[] arr,
int n, int[] q, int m)
{
// aux[i] stores no of unique elements in arr[i..n]
int []aux = new int[MAX];
// mark[i] = 1 if i has occurred
// in the suffix at least once.
int []mark = new int[MAX];
// Initialization for the last element.
aux[n - 1] = 1;
mark[arr[n - 1]] = 1;
for (int i = n - 2; i >= 0; i--)
{
if (mark[arr[i]] == 0)
{
aux[i] = aux[i + 1] + 1;
mark[arr[i]] = 1;
}
else
{
aux[i] = aux[i + 1];
}
}
for (int i = 0; i < m; i++)
{
System.out.println(aux[q[i] - 1] );
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 4, 1, 2, 3, 4, 10000, 999 };
int n = arr.length;
int q[] = { 1, 3, 6 };
int m = q.length;
printUniqueElementsInSuffix(arr, n, q, m);
}
}
// This code is contributed by Princi Singh
Python3
# Python implementation of the above approach.
MAX = 100002;
# Function to print no of unique elements
# in specified suffix for each query.
def printUniqueElementsInSuffix(arr, n, q, m):
# aux[i] stores no of unique elements in arr[i..n]
aux = [0] * MAX;
# mark[i] = 1 if i has occurred
# in the suffix at least once.
mark = [0] * MAX;
# Initialization for the last element.
aux[n - 1] = 1;
mark[arr[n - 1]] = 1;
for i in range(n - 2, -1, -1):
if (mark[arr[i]] == 0):
aux[i] = aux[i + 1] + 1;
mark[arr[i]] = 1;
else:
aux[i] = aux[i + 1];
for i in range(m):
print(aux[q[i] - 1]);
# Driver code
if __name__ == '__main__':
arr = [1, 2, 3, 4, 1, 2, 3, 4, 10000, 999];
n = len(arr);
q = [1, 3, 6];
m = len(q);
printUniqueElementsInSuffix(arr, n, q, m);
# This code is contributed by 29AjayKumar
C#
// C# implementation of the above approach.
using System;
class GFG
{
static int MAX = 100002;
// Function to print no of unique elements
// in specified suffix for each query.
static void printUniqueElementsInSuffix(int[] arr,
int n, int[] q, int m)
{
// aux[i] stores no of unique elements in arr[i..n]
int []aux = new int[MAX];
// mark[i] = 1 if i has occurred
// in the suffix at least once.
int []mark = new int[MAX];
// Initialization for the last element.
aux[n - 1] = 1;
mark[arr[n - 1]] = 1;
for (int i = n - 2; i >= 0; i--)
{
if (mark[arr[i]] == 0)
{
aux[i] = aux[i + 1] + 1;
mark[arr[i]] = 1;
}
else
{
aux[i] = aux[i + 1];
}
}
for (int i = 0; i < m; i++)
{
Console.WriteLine(aux[q[i] - 1] );
}
}
// Driver code
static public void Main ()
{
int []arr = { 1, 2, 3, 4, 1, 2, 3, 4, 10000, 999 };
int n = arr.Length;
int []q = { 1, 3, 6 };
int m = q.Length;
printUniqueElementsInSuffix(arr, n, q, m);
}
}
// This code is contributed by Sachin.
JavaScript
<script>
// javascript implementation of the above approach.
var MAX = 100002;
// Function to print no of unique elements
// in specified suffix for each query.
function printUniqueElementsInSuffix(arr, n, q, m)
{
// aux[i] stores no of unique elements in arr[i..n]
var aux =[] ;
var mark = [];
aux.length = MAX ;
mark.length = MAX ;
aux.fill(0);
mark.fill(0);
// Initialization for the last element.
aux[n - 1] = 1;
mark[arr[n - 1]] = 1;
for (var i = n - 2; i >= 0; i--)
{
if (mark[arr[i]] == 0)
{
aux[i] = aux[i + 1] + 1;
mark[arr[i]] = 1;
}
else
{
aux[i] = aux[i + 1];
}
}
for (var i = 0; i < m; i++)
{
document.write(aux[q[i] - 1] , "<br>" );
}
}
// Driver code
var arr = [ 1, 2, 3, 4, 1, 2, 3, 4, 10000, 999 ]
var n = arr.length;
var q = [ 1, 3, 6 ];
var m = q.length;
printUniqueElementsInSuffix(arr, n, q, m);
// This code is contributed by bunnyram19.
</script>
Time Complexity: O(n + m). where n and m are the sizes of the given input arrays.
Auxiliary Space: O(MAX)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem