#K15886. Longest Substring with At Most K Distinct Characters

    ID: 24456 Type: Default 1000ms 256MiB

Longest Substring with At Most K Distinct Characters

Longest Substring with At Most K Distinct Characters

Given a string \(S\) and an integer \(k\), your task is to find the length of the longest substring of \(S\) that contains no more than \(k\) distinct characters. A substring is a continuous part of the string.

For example, if \(S = \texttt{eceba}\) and \(k = 2\), the answer is 3, since the substring "ece" has length 3 and contains only 2 distinct characters ('e' and 'c').

Your solution should read input from standard input (stdin) and write the result to standard output (stdout).

Constraints:

  • \(0 \leq |S| \leq 10^5\)
  • \(0 \leq k \leq |\text{Distinct characters in } S|\)

inputFormat

The input consists of two lines:

  • The first line contains the string \(S\).
  • The second line contains the integer \(k\).

Both inputs are provided via standard input (stdin).

outputFormat

Output a single integer representing the length of the longest substring of \(S\) that contains at most \(k\) distinct characters. The output should be printed to standard output (stdout).

## sample
eceba
2
3