Longest Substring with At Most K Distinct Characters - Problem
Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
A substring is a contiguous sequence of characters within a string. The goal is to find the maximum possible length while ensuring the substring has no more than k unique characters.
Example: If s = "eceba" and k = 2, the longest substring with at most 2 distinct characters is "ece" with length 3.
Input & Output
Example 1 — Basic Case
$
Input:
s = "eceba", k = 2
›
Output:
3
💡 Note:
The longest substring with at most 2 distinct characters is "ece" with length 3. It contains only 'e' and 'c'.
Example 2 — All Same Characters
$
Input:
s = "aaaa", k = 1
›
Output:
4
💡 Note:
The entire string contains only 1 distinct character 'a', so the answer is 4.
Example 3 — Edge Case k=0
$
Input:
s = "abc", k = 0
›
Output:
0
💡 Note:
When k=0, no characters are allowed, so the longest valid substring has length 0.
Constraints
- 1 ≤ s.length ≤ 5 × 104
- 0 ≤ k ≤ 50
- s consists of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input
String s and integer k representing max distinct characters
2
Process
Find longest substring with ≤ k distinct characters
3
Output
Length of the longest valid substring
Key Takeaway
🎯 Key Insight: Use sliding window technique - expand when valid, shrink when too many distinct characters
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code