Longest substring with at most k different characters
Published on Nov 29, 2016 • Ruslan Ledesma-Garza
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
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.
Here is a Ruby implementation.
Want to read more?
I love to explain and answer questions on programming problems, the kind you find in coding interviews.
I publish a new programming problem and its solution every month.
Did I mention that I love to answer questions?