oneby7

Sliding Window Longest or shortest window

173. Longest Substring with At Most K Distinct Characters

Medium

You are given a string s and an integer k. Return the length of the longest substring of s that holds at most k different characters. A character may appear any number of times, so "noon" holds two different characters.

A substring is a block of characters that sit next to each other in s. Every character counts, including spaces, digits and punctuation, and an uppercase letter is a different character from its lowercase form.

Example 1

Input: s = "mississippi", k = 2

Output: 7

Explanation: "ississi", from index 1 to index 7, holds only i and s. Stretching it either way brings in a third character: the m before it or the p after it.

Example 2

Input: s = "zzz", k = 0

Output: 0

Explanation: Every substring holds at least one character, so none of them fits when k is 0.

Example 3

Input: s = "Hi, Bob!", k = 8

Output: 8

Explanation: The whole string holds exactly eight different characters, since B and b count as two. At most 8 includes 8, so the whole string fits.

Check your understanding

Work out the answer for this input before you write any code.

s = "aabbccbbaa", k = 2

Constraints

  • 1 ≤ s.length ≤ 105
  • s holds printable ASCII characters only: letters, digits, punctuation and the space (codes 32 to 126).
  • 0 ≤ k ≤ 105

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.