For a given string, find the length of the longest substring that contains at most k different characters.

For example, for string “abacd” and at most 2 characters, the longest substring is “aba” and thus the answer is 3.

Your task is to write a method longest that takes an integer k and a string and gives the longest substring that contains at most k different characters.

Input and output. The signature of the method is longest(k, s), where k is an integer and s is a string. The return value is an integer.

Consider the following test cases.

# Solution

Here is a Ruby implementation.

# Want to read more?

I regularly write solutions to programming problems that you may or may not find in technical job interviews. I also love to explain those solutions and answer questions. If you would like to get the latest problem + solution, subscribe to the newsletter or subscribe via RSS. You can also follow me on Twitter, GitHub, and LinkedIn.