#K34562. Shortest Substring with K Distinct Characters

    ID: 25337 Type: Default 1000ms 256MiB

Shortest Substring with K Distinct Characters

Shortest Substring with K Distinct Characters

Given an integer k and a string s, find the length of the shortest contiguous substring of s that contains exactly k distinct characters. If no such substring exists, output -1.

In other words, you need to find the minimum length of a substring for which the number of unique characters satisfies \[ |unique| = k \] If no substring meets this criteria, return \(-1\).

Example 1: For k = 2 and s = "abcba", the answer is 2 (the substring "bc" or "cb").

Example 2: For k = 3 and s = "aaabbacacca", the answer is 3 (one possible substring is "bac").

Example 3: For k = 4 and s = "aabbcc", the answer is -1 since there is no substring with exactly 4 distinct characters.

inputFormat

The input is given from stdin and has the following format:

T
k1 s1
k2 s2
...
kT sT

Here, T is the number of test cases. For each test case, an integer k and a string s is provided separated by whitespace.

outputFormat

For each test case, output the length of the shortest substring of s that contains exactly k distinct characters. If not possible, output -1. The result for each test case should be printed in a new line to stdout.

## sample
3
2 abcba
3 aaabbacacca
4 aabbcc
2

3 -1

</p>