Sliding Window Longest or shortest window
173. Longest Substring with At Most K Distinct Characters
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
7Explanation: "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
0Explanation: Every substring holds at least one character, so none of them fits when k is 0.
Example 3
Input: s = "Hi, Bob!", k = 8
8Explanation: 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.
Constraints
1 ≤ s.length ≤ 105sholds 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.