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
Input and output.
The signature of the method is
longest(k, s), where
k is an integer
s is a string. The return value is an integer.
Consider the following test cases.
Here is a Ruby implementation.
Want to read more?
I love to explain and answer questions on programming problems.
I publish a new programming problem and its solution every month.
Did I mention that I love to 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