Longest Substring with At Most K Distinct Characters
Master this topic with zero to advance depth.
Longest Substring with At Most K Distinct Characters
Given a string s and an integer k, return the length of the longest substring that contains at most k distinct characters.
Visual Representation
s = "eceba", k = 2
[e]
[e, c]
[e, c, e] (Distinct: 2 <= 2, Valid!)
[e, c, e, b] (Distinct: 3 > 2, INVALID!)Examples
Input: s = "eceba", k = 2
Output: 3
Approach 1
Level I: Brute Force
Intuition
Check every possible substring and count unique characters. Update maximum length if the count is .
⏱ O(N^2)💾 O(K)
Approach 2
Level III: Optimal (Sliding Window)
Intuition
Thought Process
Standard variable-size sliding window. Maintain a frequency map of characters in the window. When map size exceeds k, shrink from the left.
Pattern: Variable Size Sliding Window (K Distinct)
⏱ O(N)💾 O(K)
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.