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
The Sliding Window JourneyecebaaccString: "eceaaacc", k=2Window: "ece"Step 1: Window expands โ†’ "ece" (2 distinct: e,c) โœ“Step 2: Try "eceb" (3 distinct: e,c,b) โœ— Too many!Step 3: Shrink from left โ†’ "ceb" (3 distinct) still too manyStep 4: Shrink more โ†’ "eb" (2 distinct: e,b) โœ“Step 5: Continue expanding โ†’ "eba" (3 distinct) โœ—Step 6: Keep sliding and find "aaa" (1 distinct) โœ“๐Ÿ’ก Key InsightThe window only shrinks when necessary, and each characteris visited at most twice (once expanding, once shrinking)Time Complexity: O(n) | Space Complexity: O(k)This technique works for many "subarray/substring with constraint" problems!
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)

n
2n
โœ“ Linear Growth
Space Complexity
O(k)

Hash map stores at most k+1 distinct characters

n
2n
โœ“ 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?
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28 Apple 22
52.4K Views
High Frequency
~22 min Avg. Time
1.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