Longest Substring with At Most K Distinct Characters - Problem
You are given a string s and an integer k, and your task is to find the length of the longest substring that contains at most k distinct characters.
A substring is a contiguous sequence of characters within a string. For example, in the string "abcdef", some substrings include "abc", "cde", and "def".
Goal: Return the maximum length of any substring that has at most k unique characters.
Example: If s = "eceba" and k = 2, the answer is 3 because the substring "ece" has exactly 2 distinct characters ('e' and 'c') and is the longest such substring.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "eceba", k = 2
โบ
Output:
3
๐ก Note:
The longest substring with at most 2 distinct characters is "ece" which has length 3. It contains only 2 distinct characters: 'e' and 'c'.
example_2.py โ All Same Characters
$
Input:
s = "aaaa", k = 1
โบ
Output:
4
๐ก Note:
The entire string "aaaa" has only 1 distinct character 'a', which is โค k=1, so the answer is the full length 4.
example_3.py โ k=0 Edge Case
$
Input:
s = "abc", k = 0
โบ
Output:
0
๐ก Note:
When k=0, we cannot have any distinct characters, so no valid substring exists. The answer is 0.
Visualization
Tap to expand
Understanding the Visualization
1
Start Reading
Place your window at the beginning and start reading characters one by one
2
Expand Window
Keep widening your view to the right as long as you see at most k different characters
3
Hit the Limit
When you see too many different characters, slide the left edge of your window right
4
Track Maximum
Remember the largest window size you've seen that met the constraint
Key Takeaway
๐ฏ Key Insight: The sliding window technique transforms a potentially O(nยณ) brute force solution into an elegant O(n) algorithm by maintaining state efficiently and only shrinking the window when absolutely necessary.
Time & Space Complexity
Time Complexity
O(n)
Each character is visited at most twice (once by right pointer, once by left pointer)
โ Linear Growth
Space Complexity
O(k)
Hash map stores at most k+1 distinct characters
โ Linear Space
Constraints
- 1 โค s.length โค 5 ร 104
- 0 โค k โค 50
- s consists of English letters
- Follow up: Could you solve it in O(n) time?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code