Longest Substring with At Most K Distinct Characters
Longest Substring with At Most K Distinct Characters
Sliding WindowHash Map
Problem Statement
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
Example 1:
Input: s = "eceba", k = 2
s: "eceba", k: 2
Output: 3
Output: 3
The substring is "ece" with length 3.
Solution
This problem can be solved using a sliding window and a hash map. The hash map will store the frequency of characters in the current window. We expand the window by moving the right pointer. If the number of distinct characters in the map exceeds `k`, we shrink the window from the left until the condition is met again.
Algorithm Steps
- Initialize `maxLength` to 0, a left pointer `l` to 0, and a hash map `charCount`.
- Iterate through the string with a right pointer `r`.
- Add the character `s[r]` to the hash map and increment its count.
- While the number of distinct characters in the hash map is greater than `k`:
- Decrement the count of the character `s[l]` in the map.
- If the count becomes 0, remove the character from the map.
- Increment `l`.
- Update `maxLength` with the maximum of `maxLength` and the current window size (`r - l + 1`).
Longest Substring with At Most K Distinct Characters
Sliding Window with Hash Map
Progress1 / 1
Ready to start the visualization
s
e
c
e
b
a
Hash Map (char: count)
Max Length
0
Longest Substring with At Most K Distinct Characters Solution