Longest Substring with At Most K Distinct Characters

medium

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

Hints

This is Fruit Into Baskets with k baskets instead of two.
Keep a count map of the window's characters; its size is the distinct count.
Grow the right edge; when the map has more than k keys, shrink from the left.

Common doubts

Only the threshold: fruit fixes it at 2, this compares the count-map size to a parameter k. The algorithm is otherwise identical.
So the map's key-count stays equal to the number of distinct characters currently in the window.
Zero — no character is permitted, so the shrink loop empties any window immediately and the best stays 0.

Interview follow-ups

Compute 'at most k' minus 'at most k-1' — the count of substrings (or lengths) with exactly k distinct falls out of two at-most windows.
The map never holds more than k+1 entries, so space is O(k) — independent of the string length.

Fun facts

  • The 'at most k distinct' window is a workhorse: fruit baskets, this problem, and 'subarrays with exactly k distinct' all reduce to it.
  • Subtracting two at-most-k windows to get exactly-k is a neat inclusion-exclusion trick worth remembering.

Asked at

GoogleAmazonMetaMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: s = "eceba", k = 2
Output: 3
The longest substring with at most 2 distinct characters is "ece", of length 3.
Example 2
Input: s = "aa", k = 1
Output: 2
The whole string "aa" has one distinct character.
Constraints

- 0 <= s.length <= 5 * 10^4 - 0 <= k <= 50 - s consists of lowercase English letters.

Solve this problem →