Skip to content
Decoder

Longest Substring with At Most K Distinct Characters

Medium

Problem

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

Example 1

Input
s = "eceba", k = 2
Output
3
Why
"ece"

Example 2

Input
s = "aa", k = 1
Output
2

Example 3

Input
s = "abaccc", k = 2
Output
4
Why
"accc"

Constraints

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

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.