Dsa
Prefix Sum
Medium
Count Distinct Elements in Ranges
Implement a program that counts distinct elements within specified ranges in an array. You will use a prefix sum approach to build an efficient query mechanism that outputs the number of distinct integers in subarrays defined by given ranges.
Input format:
- The first line contains two integers n (array size) and q (number of queries).
- The second line contains n space-separated integers of the array.
- The next q lines provide the range queries in the format 'start end'.
Output format:
- For each query, print the count of distinct elements in the specified range on a new line.
Example:
Input:
5 3
1 2 2 1 3
1 3
0 4
2 4
Output:
3
4
3
Key concepts
prefix_sumdistinct_countrange_query
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now