#K66362. Shortest Subarray with Exactly K Distinct Integers
Shortest Subarray with Exactly K Distinct Integers
Shortest Subarray with Exactly K Distinct Integers
You are given an array of integers. Your task is to find the length of the shortest contiguous subarray that contains exactly \(K\) distinct integers. If no such subarray exists, output -1.
Explanation: For a given array A of length N and an integer K, you need to find indices i and j (with 0 \(\leq i \leq j < N\)) such that the subarray A[i...j] contains exactly \(K\) distinct values and its length (j - i + 1) is minimized.
If there is no contiguous subarray that satisfies the condition, print -1
.
Note: Make sure to handle multiple test cases as described in the input section.
inputFormat
The input is given via standard input (stdin) and has the following format:
T N1 K1 A1,1 A1,2 ... A1,N1 N2 K2 A2,1 A2,2 ... A2,N2 ... NT KT AT,1 AT,2 ... AT,NT
Here, T is the number of test cases. For each test case, the first line contains two integers: N, the number of elements in the array, and K, the number of distinct integers required in the subarray. The next line contains N space-separated integers representing the array.
outputFormat
For each test case, output the length of the shortest contiguous subarray that contains exactly \(K\) distinct integers. If such a subarray doesn't exist, output -1
.
The outputs for all test cases should be printed on separate lines via standard output (stdout).
## sample3
10 3
1 2 1 2 3 4 5 6 7 8
5 5
1 1 2 2 3
8 4
1 2 3 3 4 2 1 5
3
-1
4
</p>