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.See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI