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 Characters INPUT String s: e 0 c 1 e 2 b 3 a 4 k = 2 Find longest substring with at most k=2 distinct characters ALGORITHM STEPS 1 Initialize HashMap, left=0, maxLen=0 2 Expand Window Add char to map, count++ 3 Shrink if Needed While distinct chars > k 4 Update Maximum maxLen = max(maxLen, len) HashMap State (window "ece"): 'e' : 2 'c' : 1 2 distinct Window: [left, right] [0, 2] --> "ece" (len=3) FINAL RESULT Longest valid substring found: e c e b a Substring: "ece" (indices 0-2) Output: 3 Verification: "ece" has 2 distinct chars {'e', 'c'} <= k=2 [OK] Length = 3 (maximum) Key Insight: The sliding window with HashMap tracks character frequencies. When distinct count exceeds k, shrink from left until valid. This gives O(n) time complexity as each character is added/removed at most once. TutorialsPoint - Longest Substring with At Most K Distinct Characters | Hash Map Approach
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