Loading problem...
You are given a string s consisting of lowercase and/or uppercase English letters, and a non-negative integer k representing the maximum allowable count of distinct characters.
Your task is to determine the length of the longest contiguous segment (substring) within s such that the total number of unique characters within that segment does not exceed k.
A substring is a contiguous sequence of characters within the string. For example, in the string "abcde", valid substrings include "a", "bcd", "abcde", but "ace" is not a substring (it is a subsequence).
The distinct character count of a substring refers to the number of different characters present in that substring. For instance, "abcab" has 3 distinct characters: 'a', 'b', and 'c'.
Return the maximum length of any valid substring that satisfies the constraint of having at most k distinct characters. If k is 0, the only valid substring is an empty one, so return 0.
s = "eceba"
k = 23The longest substring with at most 2 distinct characters is "ece", which has exactly 2 unique characters ('e' and 'c') and a length of 3. Other valid substrings like "ec" or "ba" exist but are shorter.
s = "aa"
k = 12The entire string "aa" contains only 1 distinct character ('a'), which satisfies the constraint k = 1. Therefore, the maximum length is 2.
s = "abcabcbb"
k = 38The entire string "abcabcbb" contains exactly 3 distinct characters ('a', 'b', 'c'), which exactly meets the constraint k = 3. Thus, the entire string of length 8 is the longest valid substring.
Constraints