Longest Substring with At Most K Distinct Characters
1 approach, code in every language
Problem description
Given a string s and an integer k, find the length of the longest contiguous substring that contains no more than k distinct characters.
If k is zero, no characters may appear, so the answer is zero.
Example 1
Input: s = "eceba", k = 2
Output: 3
The block "ece" uses only the two distinct characters e and c.
Example 2
Input: s = "aabbcc", k = 1
Output: 2
With only one distinct character allowed, a run like "aa" is the longest possible.
Constraints
1 <= s.length <= 5 * 10^40 <= k <= 5 * 10^4s consists of English letters.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Longest Belt Run Within a Colour Budget is our own problem on the technique behind Longest Substring with At Most K Distinct Characters: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free