Longest Substring with K Distinct Characters
Sliding Window
Problem
Given a string, find the length of the longest substring in it with no more than K distinct characters.
For example:
Thought Process
How can we keep track of distinct characters?
By using a dictionary and keeping track of character frequency
We use a dictionary to keep track of distinct characters along with their count
We only move the sliding window forward when the length of the dictionary surpasses k because this means we have more distinct characters than k.
We shrink the sliding window until we are left with 'k' distinct characters in our dictionary
Solution
Key Points
Using a dynamic window that is static according to the numbers of distnict characters we have
The length of our dictionary controls when we move/increment the sliding window
We use a while loop in order to continuously shrink the sliding window until we meet our condition (which in this case is k distinct characters)
Time complexity
Time: where n is the length ofthe string
Space: where K is the distinct characters classified because at most we will be storing K+1 characters in hash map.
Last updated
Was this helpful?