#C3917. Longest Substring with Exactly k Unique Characters

    ID: 47397 Type: Default 1000ms 256MiB

Longest Substring with Exactly k Unique Characters

Longest Substring with Exactly k Unique Characters

Given a string s and an integer k, the task is to determine the length of the longest substring of s that contains exactly k unique characters.

If no such substring exists, output -1.

The problem can be approached using the sliding window technique. As you traverse the string, maintain a window that contains at most k distinct characters. When the window exceeds k unique characters, shrink it from the left until it has at most k unique characters. During this process, if the window has exactly k unique characters, record the length of the window. The final answer is the maximum recorded length, or -1 if no valid window is found.

Examples:

  • Input: s = "araaci", k = 2 → Output: 4
  • Input: s = "araaci", k = 1 → Output: 2
  • Input: s = "cbbebi", k = 3 → Output: 5
  • Input: s = "abcde", k = 10 → Output: -1

inputFormat

The input is given via stdin in two lines:

  1. The first line contains the string s consisting of lowercase and/or uppercase letters.
  2. The second line contains the integer k.

outputFormat

Output a single integer to stdout representing the length of the longest substring with exactly k unique characters. If no valid substring exists, output -1.

## sample
araaci
2
4