Longest Substring with At Most K Distinct Characters

Medium · Sliding Window · Hash Table · String · Sliding Window

Problem

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

A substring is a contiguous run of characters. Uppercase and lowercase letters count as different characters. If k is 0, no non-empty substring qualifies and the answer is 0.

Examples

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

"accc" uses only a and c and is longer than "aba".

Input: s = "aa", k = 0
Output: 0

No character may be used, so only the empty substring qualifies.

Input: s = "eceba", k = 2
Output: 3

"ece" uses e and c. Adding b on the right would make three letters.

Constraints

Approaches

Follow-up

What if the characters arrive as a stream and you can only keep O(k) memory? Keep, for each character in the window, the index of its last occurrence (an ordered map from character to last index). When a (k + 1)-th character arrives, the new window starts just after the smallest last index, which you can evict without remembering the text itself.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…