Smallest Subarray with K Distinct Elements Problem
Given an array A
consisting of N
integers, find the smallest subarray of A
that contains exactly K
distinct integers.
Input:
The first line contains two integers N
and K
, denoting the total number of integers and the number of distinct integers respectively.
The second line contains N
space-separated integers describing the elements of the array A
.
Output:
Output two space-separated integers denoting the starting and ending indices of the subarray if it exists; otherwise, print -1
.
Example:
Suppose A = [1, 2, 2, 3, 1, 3]
and K = 2
. The smallest subarrays with 2 distinct elements include [1,2]
, [2,3]
, [3,1]
, and [1,3]
. The preferred subarray based on the smallest starting index is [1,2]
, which starts and ends at indices 0
and 1
, respectively.
Constraints:
1 <= N, K <= 10^6
-10^5 <= A[i] <= 10^5
- Time limit: 1 sec
Note:
You do not need to print anything; it has already been taken care of. Just implement the given function. Assume the array starts at index 0. If multiple solutions are possible, select the subarray with the smaller starting index.


Find the smallest subarray with exactly K distinct integers in an array.
Use a sliding window approach to keep track of the subarray with K distinct integers.
Use a hashmap to store the frequency of eac...read more


Top Uber SDE-2 interview questions & answers
Popular interview questions of SDE-2
Reviews
Interviews
Salaries
Users/Month