Longest Substring with At Most K Distinct Characters (LeetCode 340): Solution and Explanation

Medium
Hash Table
String
Sliding Window

Given a string and an integer k, find the length of the longest contiguous substring that uses no more than k different characters.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

A brute force checks every starting index, extends the substring to the right while tracking the set of distinct characters, and stops once that set grows past k. That is O(n²) in the worst case, since each start can scan almost the whole string. The waste is that neighboring start positions repeat nearly the same scan.

The fix comes from a monotonic property. If a window has at most k distinct characters, every smaller window inside it does too. And if a window has too many, extending it to the right can only keep it invalid. So you never need to move the left edge backward. That is the condition for the sliding window technique: grow the window from the right, and when it breaks the rule, shrink it from the left until it is valid again.

To know how many distinct characters are in the window, keep a map from character to its count inside the window. Adding the right character increments its count. Removing the left character decrements its count, and when a count hits zero you delete the key, so the number of keys in the map is exactly the number of distinct characters. After each adjustment the window is the longest valid one ending at the current right index, so you record its length.

Both pointers only move forward, and each character enters and leaves the window at most once, so the whole thing runs in linear time.

Approach: Sliding window with a count map

  1. If k == 0, return 0, since no character is allowed.
  2. Set up an empty char_count map, left = 0 and max_len = 0.
  3. For each right index, increment the count of s[right].
  4. While the map has more than k keys, decrement the count of s[left], delete it when it reaches zero, and move left forward.
  5. Update max_len with right - left + 1.
  6. Return max_len after the loop.

Step-by-step example

s = "eceba", k = 2
  1. right = 0 adds e: the window is "e" with counts {e: 1}, so max_len = 1.
  2. right = 1 adds c: {e: 1, c: 1}, two distinct, window "ec", so max_len = 2.
  3. right = 2 adds e: {e: 2, c: 1}, window "ece", so max_len = 3.
  4. right = 3 adds b: three distinct. Removing s[0] = e leaves {e: 1, c: 1, b: 1}, still three. Removing s[1] = c deletes c, leaving {e: 1, b: 1} with left = 2 and window "eb".
  5. right = 4 adds a: three distinct again. Removing s[2] = e deletes it, leaving {b: 1, a: 1} with window "ba". The answer stays 3, for "ece".

Code: Python, Java, C++

1class Solution:
2    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
3        if k == 0:
4            return 0
5
6        char_count = {}
7        left = 0
8        max_len = 0
9
10        for right in range(len(s)):
11            char_count[s[right]] = char_count.get(s[right], 0) + 1
12
13            while len(char_count) > k:
14                char_count[s[left]] -= 1
15                if char_count[s[left]] == 0:
16                    del char_count[s[left]]
17                left += 1
18
19            max_len = max(max_len, right - left + 1)
20
21        return max_len

Time and space complexity

Time

O(n)

The right pointer visits each character once and the left pointer advances at most n times in total, with constant-time map updates.

Space

O(k)

The map holds at most k + 1 distinct characters at any moment.

Other approaches

Brute force with a set (time O(n²), space O(k))

For each start index, extend right while the distinct set stays within k. Easy to write but quadratic.

Window that never shrinks (time O(n), space O(k))

Replace the inner while with a single if, so the window slides forward at its best size instead of shrinking. The answer is the final window length, n - left. It does constant work per step and is a neat trick for streaming input.

Common mistakes

  • Forgetting to delete keys whose count drops to zero, so len(char_count) overcounts distinct characters.
  • Updating max_len before shrinking the window, which records a length for an invalid window.
  • Using an if instead of a while for shrinking while still taking right - left + 1 as the answer; that can report a window with too many distinct characters.
  • Not handling k = 0, which should return 0 immediately.

Frequently asked questions

How does the sliding window solve this problem?

The window grows to the right one character at a time and shrinks from the left only when it holds more than k distinct characters. The longest window seen while valid is the answer.

Why is the time complexity O(n) with a nested while loop?

The inner loop only moves the left pointer forward, and it can move forward at most n times over the whole run. So the total work across both loops is linear.

How is this related to longest substring without repeating characters?

Both use the same expand and shrink window. That problem requires every character count to be at most one, while this one limits the number of distinct characters to k.

What changes for exactly k distinct characters?

Count windows with at most k distinct and subtract those with at most k - 1. For the longest length, simply only record windows whose map has exactly k keys.