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
Longest Substring with At Most K Distinct CharactersInput: s = "eceba", k = 2ecebaLongest: "ece"Distinct characters: {e, c} ≤ k=2 ✓Length: 3Other substrings:"e" → length 1"ec" → length 2"eceb" → 3 distinct ✗Output: 3🎯 Key Insight: Use sliding window to maintain valid substring efficiently
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
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
156.0K Views
High Frequency
~18 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen