Skip to content

Longest Substring with At Most K Distinct Characters

MediumSliding Window
Decode it first. Clues, constraints, pattern and plan before any code.

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

s = "eceba",  k = 2   →  3   ("ece")
s = "aa",     k = 1   →  2
s = "abaccc", k = 2   →  4   ("accc")

Constraints

  • 1 <= s.length <= 5 * 10^4
  • 0 <= k <= 50