All problems

Problem 333

Longest Substring with At Most K Distinct

Medium · 20 pts · String, Sliding Window, Hash Table

Problem

Find the length of the longest substring (contiguous) that contains at most K different characters. A sliding window works well: extend the window to the right, and whenever it holds more than K distinct characters, shrink it from the left until it is valid again.

Input

First line: the string S of lowercase letters. Second line: integer K.

Output

Print the length of the longest valid substring.

Constraints

1 <= |S| <= 100000; 1 <= K <= 26

Example input

eceba
2

Example output

3

Explanation

With K = 2 in 'eceba', the substring 'ece' uses only the letters e and c and has length 3, the longest possible.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum Steps to Make Anagram Next: Palindrome Pairs Count