Longest Substring with At Most K Distinct Characters

Medium Sliding Window

s is a string of letters and digits, and k is a whole number.

A substring is a run of characters that sit next to each other in s, with none skipped. It may use at most k different characters, repeating each as often as it likes. Upper case and lower case letters are different characters, so a and A count as two.

Return the length of the longest substring that follows this rule. When k is 0 no character is allowed, so the answer is 0.

Example 1

Input: s = "xxyzzzyx", k = 2
Output: 5

The substring yzzzy has two different characters and is 5 long; adding the x on either side would make three.

Example 2

Input: s = "AaAaBb", k = 2
Output: 4

Example 3

Input: s = "k9k9k", k = 5
Output: 5

Constraints

  • 1 ≤ s.length ≤ 10⁵
  • s holds only letters (a–z, A–Z) and digits (0–9)
  • 0 ≤ k ≤ 62

More Sliding Window

All Sliding Window problems