You are given an array ‘ARR’ having ‘N’ integers. You are also given an integer ‘K’. The task is to count the number of subarrays that have ‘K’ distinct values.
Subarray: A consecutive sequence of one or more values taken from an array.
‘N’ = 4, ‘K’ = 2
‘ARR’ = [1, 1, 2, 3]
There are ‘3’ subarrays with ‘2’ distinct elements, which are as follows: [1, 2], [2, 3], [1, 1, 2].
Thus, you should return ‘3’ as the answer.
The first line contains two integers, ‘N’ and ‘K’.
The second line contains ‘N’ integers representing the array ‘ARR’.
Output Format :
Print the number of subarrays that have exactly ‘K’ distinct values.
Note :
You do not need to print anything, it has already been taken care of. Just implement the function.
5 2
2 1 3 2 4
9
There are ‘4’ subarrays with exactly ‘2’ distinct elements, which are as follows: [2, 1], [1, 3], [3, 2], [2, 4].
Thus, you should return ‘4’ as the answer.
5 4
1 2 3 4 5
2
1 <= K <= N <= 10^5
1 <= Value in each element of ‘ARR’ <= 10^9
Time limit: 1 second
Find all the possible subarrays of ‘ARR’.
We can generate all the subarrays of ‘ARR’ using two nested loops. In the outer loop, use a hash map to store the distinct values in the subarrays generated in the inner loop. If a subarray ‘[L, R]’ has more than ‘K’ distinct values, then all the subarrays ‘[L, R+1], [L, R+2], .., [L, N-1]’ will also have more than ‘K’ distinct values. So, we don’t need to check these subarrays.
Algorithm
O(N^2), where ‘N’ is the size of array ‘ARR’.
There are ‘N*(N+1)/2’ possible subarrays, and in the worst-case, every subarray will have at most ‘K’ distinct values. Thus, the time complexity will be ‘O(N^2)’.
O(N), where ‘N’ is the size of array ‘ARR’.
The hash map used in each iteration will store at most ‘N’ values (when all the values in ‘ARR’ are distinct). Thus, the space complexity is ‘O(N)’.