VOOZH about

URL: https://www.geeksforgeeks.org/dsa/queries-for-number-of-distinct-elements-in-a-subarray-set-2/

⇱ Queries for number of distinct elements in a subarray | Set 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Queries for number of distinct elements in a subarray | Set 2

Last Updated : 11 Jul, 2025

Given an array arr[] of N integers and Q queries. Each query can be represented by two integers L and R. The task is to find the count of distinct integers in the subarray arr[L] to arr[R].
Examples:

Input: arr[] = {1, 1, 3, 3, 5, 5, 7, 7, 9, 9 }, L = 0, R = 4 
Output: 3
Input: arr[] = { 1, 1, 2, 1, 3 }, L = 1, R = 3 
Output :

Naive approach: In this approach, we will traverse through the range l, r, and use a set to find all the distinct elements in the range and print them. 
Time Complexity: O(q*n)
Efficient approach: Idea is to form a segment tree in which the nodes will store all the distinct elements in the range. For this purpose, we can use a self-balancing BST or "set" data structure in C++. 
Each query will return the size of the set.
Below is the implementation of the above approach: 
 


Output: 
3

 

Time Complexity: O(q*n*log(n)), where n is the size of the input array.

Auxiliary space: O(n*log(n)), as the segment tree has 2n-1 nodes and each node contains a set of distinct elements.

Comment