#K88227. Shortest Prefix with K Distinct Characters

    ID: 37262 Type: Default 1000ms 256MiB

Shortest Prefix with K Distinct Characters

Shortest Prefix with K Distinct Characters

Given a string S and an integer K, your task is to find the length of the shortest prefix of S that contains at least K distinct characters. If no such prefix exists, output -1.

The prefix of a string is defined as the starting substring. For example, the prefixes of "abcabc" are "a", "ab", "abc", "abca", etc.

The problem can be formulated using the following equation: \[ ans = \min\{ i \mid |\{ S_1, S_2, \dots, S_i \}| \ge K \} \] where \(|\{ S_1, S_2, \dots, S_i \}|\) represents the number of unique characters in the first i characters of S.

If such an index does not exist, output -1.

inputFormat

The input is read from stdin and consists of:

  1. A single string S (consisting of lowercase/uppercase letters or any characters without spaces).
  2. An integer K on the same line or on the next line, representing the threshold of distinct characters.

Both values are separated by whitespace.

outputFormat

Output to stdout a single integer: the length of the shortest prefix of S that contains at least K distinct characters. If no such prefix exists, output -1.

## sample
abcabc 3
3

</p>