Given a string s and an integer k, return the length of the longest substring of s that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Explanation: The substring is "ece" with length 3.
Example 2:
Input: s = "aa", k = 1
Output: 2
Explanation: The substring is "aa" with length 2.
Constraints:
code
1 <= s.length <= 5 * 10^4
0 <= k <= 50
solve in python
Assistant
To solve the problem of finding the length of the longest substring with at most k distinct characters, we can employ the Sliding Window technique. This approach efficiently traverses the string while maintaining a window that satisfies the given condition.
Approach
Sliding Window Basics:
We use two pointers, left and right, to define the current window in the string.
right expands the window by moving forward, while left shrinks the window when the condition is violated.
Hashmap to Track Characters:
A dictionary (char_count) keeps track of the frequency of each character within the current window.
This helps in quickly determining the number of distinct characters in the window.
Maintaining the Window:
As we move right through the string, we add characters to char_count.
If the number of distinct characters exceeds k, we move left forward to reduce the number of distinct characters, updating char_count accordingly.
Recording the Maximum Length:
Throughout the process, we keep updating the max_length to record the length of the longest valid substring found.
Edge Cases:
k = 0: No characters are allowed, so the result is 0.
k >= number of unique characters in s: The entire string is valid.
Empty String: Although the constraints specify 1 <= s.length, it's good practice to handle it gracefully.
Implementation
Below is the Python implementation of the above approach:
python
def length_of_longest_substring_k_distinct(s: str, k: int) -> int:
if k == 0:
return 0
n = len(s)
left = 0
right = 0
max_length = 0
char_count = {}
while right < n:
# Add the current character to the dictionary
current_char = s[right]
char_count[current_char] = char_count.get(current_char, 0) + 1
# If we have more than k distinct characters, shrink the window from the left
while len(char_count) > k:
left_char = s[left]
char_count[left_char] -= 1
if char_count[left_char] == 0:
del char_count[left_char]
left += 1
# Update the maximum length found
current_window_length = right - left + 1
if current_window_length > max_length:
max_length = current_window_length
right += 1
return max_length
# Example usage:
if __name__ == "__main__":
# Example 1
s1 = "eceba"
k1 = 2
print(f"Input: s = \"{s1}\", k = {k1}")
print(f"Output: {length_of_longest_substring_k_distinct(s1, k1)}") # Expected: 3 ("ece")
# Example 2
s2 = "aa"
k2 = 1
print(f"\nInput: s = \"{s2}\", k = {k2}")
print(f"Output: {length_of_longest_substring_k_distinct(s2, k2)}") # Expected: 2 ("aa")
# Additional Test Cases
s3 = "aabbcc"
k3 = 2
print(f"\nInput: s = \"{s3}\", k = {k3}")
print(f"Output: {length_of_longest_substring_k_distinct(s3, k3)}") # Expected: 4 ("aabb" or "bbcc")
s4 = "abcadcacacaca"
k4 = 3
print(f"\nInput: s = \"{s4}\", k = {k4}")
print(f"Output: {length_of_longest_substring_k_distinct(s4, k4)}") # Expected: 11 ("cadcacacaca")
Explanation of the Code
Initialization:
left and right pointers start at 0.
max_length keeps track of the maximum substring length found.
char_count is an empty dictionary to store character frequencies.
Expanding the Window:
We iterate right from 0 to n-1, adding each character to char_count.
Shrinking the Window:
If the number of distinct characters exceeds k, we move the left pointer to the right, decrementing the count of the character being left behind.
If a character's count drops to 0, it is removed from char_count.
Updating Maximum Length:
After ensuring the window has at most k distinct characters, we calculate the current window's length and update max_length if necessary.
Final Result:
After traversing the entire string, max_length holds the length of the longest valid substring.
Testing the Code
The provided if __name__ == "__main__": block includes test cases:
Example 1:
Input: s = "eceba", k = 2
Output: 3 ("ece")
Example 2:
Input: s = "aa", k = 1
Output: 2 ("aa")
Additional Test Cases:
"aabbcc" with k = 2 should return 4 ("aabb" or "bbcc").
"abcadcacacaca" with k = 3 should return 11 ("cadcacacaca").
Running the code will display the expected outputs, verifying the correctness of the implementation.