Longest Substring with At Most K Distinct Characters

Medium

Topics
StringSliding WindowHash Table

Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.

Example 1

e0c1e2b3a4
Input:  s = "eceba", k = 2
Output: 3
Explanation: The substring "ece" has 2 distinct characters and length 3.

Example 2

a0a1
Input:  s = "aa", k = 1
Output: 2
Explanation: The whole string has only 1 distinct character.

Example 3

a0b1c2
Input:  s = "abc", k = 0
Output: 0
Explanation: No substring can have zero distinct characters except the empty one.

Constraints

  • 1 <= s.length <= 5 * 10^4
  • 0 <= k <= 50
  • s consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls

Intuition

The "at most k distinct" property is monotone: shrinking a valid window keeps it valid, and growing an invalid one keeps it invalid. That is exactly the condition a variable-size sliding window needs. Extend the right edge greedily, and whenever the distinct count exceeds k, advance the left edge until it does not. Every index enters and leaves the window once, so this is linear even though it looks quadratic.

Approach

  1. Keep a counter of how many times each character occurs inside the current window, and track how many distinct characters that map holds.
  2. Move right forward one character at a time, incrementing its count and bumping the distinct total when the count goes from 0 to 1.
  3. While the distinct total exceeds k, decrement the count at left and advance it. When a count falls to 0, remove the key and drop the distinct total.
  4. After each right-edge step, the window is valid, so update the best answer with right - left + 1.
class Solution:
    def lengthOfLongestSubstringKDistinct(self, s, k):
        if k == 0:
            return 0
        count = {}
        left = 0
        best = 0
        for right, ch in enumerate(s):
            count[ch] = count.get(ch, 0) + 1
            while len(count) > k:
                drop = s[left]
                count[drop] -= 1
                if count[drop] == 0:
                    del count[drop]
                left += 1
            best = max(best, right - left + 1)
        return best

Dry Run

s = "eceba", k = 2
  r=0 add e   counts {e:1}         left 0   window "e"    len 1   best 1
  r=1 add c   counts {e:1, c:1}    left 0   window "ec"   len 2   best 2
  r=2 add e   counts {e:2, c:1}    left 0   window "ece"  len 3   best 3
  r=3 add b   three distinct, shrink: e down to 1, then c evicted
              counts {e:1, b:1}    left 2   window "eb"   len 2   best 3
  r=4 add a   shrink: e evicted
              counts {b:1, a:1}    left 3   window "ba"   len 2   best 3
answer 3   --  "ece"
Row r=3 shows why the map holds counts and not just a set of characters. Two
evictions happen there: the e at index 0 leaves, but another e remains at index 2,
so the key survives with count 1. Only c actually departs. Delete a key on the
first decrement and the window would believe it had dropped a character it still
contains.
The opposite error is the one that bites harder. Leave zero-count keys in the map
and `len(counts)` never falls back below k, so the shrink loop runs past the right
edge of the window -- this input dies with KeyError rather than returning a
wrong-but-plausible length.
The `k <= 0` guard is defensive rather than load-bearing, which is worth knowing
before you treat it as the fix for something. The stated constraint is
0 <= k <= 50, and at k = 0 the shrink loop simply drains the window, leaving
left at right + 1 and best at 0 -- the correct answer, with or without the guard.
It only changes behaviour for negative k, which cannot occur.
The best length is recorded AFTER shrinking, which is what guarantees it measures
a valid window rather than the oversized one that triggered the shrink.

Complexity

  • Time — O(n) — each pointer only moves forward, so at most 2n steps.
  • Space — O(k) — the map never holds more than k + 1 keys.

Common Pitfalls

  • The k <= 0 guard is defensive, not load-bearing — worth knowing before you treat it as the fix for something. At k = 0 the shrink loop simply drains the window, leaving left at right + 1 and the answer at 0 with or without it. It only changes behaviour for negative k, which the stated constraint 0 <= k <= 50 rules out.
  • Delete a key when its count reaches zero. Leaving zero-count entries in the map means len(counts) never falls back below k, so the shrink loop walks off the right edge of the window — on eceba with k = 2 that is a KeyError, not a wrong-but-plausible length.
  • Use while, not if, for the shrink step — though with one insertion per iteration a single shrink suffices, the while is what makes the invariant obvious and survives the k-element variants.
  • Record the best length after shrinking, not before, or you measure an invalid window.

Full Solution — all languages

class Solution:
    def lengthOfLongestSubstringKDistinct(self, s, k):
        if k <= 0:
            return 0
        counts = {}
        left = 0
        best = 0
        for right, c in enumerate(s):
            counts[c] = counts.get(c, 0) + 1
            while len(counts) > k:
                drop = s[left]
                counts[drop] -= 1
                if counts[drop] == 0:
                    del counts[drop]
                left += 1
            best = max(best, right - left + 1)
        return best
SensAI
Beta
Tap the mic to stop voice mode