#K55542. Smallest Substring with K Distinct Characters

    ID: 29998 Type: Default 1000ms 256MiB

Smallest Substring with K Distinct Characters

Smallest Substring with K Distinct Characters

You are given a string S and an integer K. Your task is to determine the length of the smallest contiguous substring of S that contains exactly K distinct characters. If no such substring exists, output -1.

Formally, you need to find the minimal length L such that there exists a substring S[i...j] (with j - i + 1 = L) where the number of distinct characters is exactly K. The answer should be output as a single integer.

Note: All input and output should be handled via standard input and standard output.

inputFormat

The input consists of two lines:

  • The first line contains the string S.
  • The second line contains the integer K.

You may assume that S consists of only lowercase letters and that K is a positive integer.

outputFormat

Output a single integer representing the length of the smallest substring of S that contains exactly K distinct characters. If no such substring exists, output -1.

## sample
abcaa
2
2

</p>