Intermediate Level
Implement the longestSubstringWithKDistinct method that returns the longest substring length with at most k distinct characters.
The input contains a string text and an integer k. Your task is to find the length of the longest contiguous substring that contains at most k distinct characters.
A substring must be continuous, so characters cannot be skipped.
For example, in eceba with k = 2, the longest valid substring is ece, so the answer is 3.
Use a sliding window with a frequency map.
Expand the right side of the window by adding characters. If the window contains more than k distinct characters, move the left side forward until the window becomes valid again.
Whenever the window is valid, update the longest length found so far.
Pseudocode:
function longestSubstringWithKDistinct(text, k):
if k == 0:
return 0
left = 0
best = 0
frequency = empty map
for right from 0 to length of text - 1:
add text[right] to frequency
while number of keys in frequency > k:
decrease frequency of text[left]
if frequency of text[left] becomes 0:
remove text[left] from frequency
left++
best = maximum(best, right - left + 1)
return best