#K16171. Longest Substring with Exactly K Unique Characters

    ID: 24520 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, find the length of the longest substring that contains exactly k unique characters. If no such substring exists, return -1.

Formally, let \( s = s_1 s_2 \ldots s_n \) be the input string. We are to find the maximum length \( L \) such that there exists indices \( i \) and \( j \) with \( 1 \leq i \leq j \leq n \) and

[ L = j - i + 1, \quad |{ s_i, s_{i+1}, \ldots, s_j }| = k. ]

If no such substring exists, output (-1).

Note: The input string may be empty, and \( k \) can be zero. In these cases, proper handling is required as described in the examples below.

inputFormat

The input consists of two lines:

  1. The first line contains a non-negative string s (which may contain spaces).
  2. The second line contains an integer k.

You should read input from stdin.

outputFormat

Output a single integer representing the length of the longest substring of s that contains exactly k unique characters. If no such substring exists, print -1.

The output should be written to stdout.

## sample
araaci
2
4