26. Longest K unique characters substring
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
I have used a sliding window technique to find the longest substring with at most K unique characters.
I maintained a sliding window represented by two pointers, i
and j
.
I used a hash map cnt
to keep track of the frequency of characters within the window.
I incremented c
whenever a new unique character was encountered within the window.
When c
exceeded k
, I moved the starting i
pointer to shrink the window and maintain at most k
unique characters.
I updated the out
variable whenever c
became equal to k
to keep track of the longest valid substring.
Let's take the input string "aabacbebebe"
and k = 3
as an example:
Hence the Longest K = 3
unique characters substring for this string is 7
.
Time Complexity: The code runs in O(N)
time, where N
is the length of the input string s
. This is because both the i
and j
pointers traverse the string once.
Auxiliary Space Complexity: The code uses an unordered_map cnt
to store character frequencies, which can have at most K
unique characters. Therefore, the space complexity is O(K)
.
For discussions, questions, or doubts related to this solution, please visit our . We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the repository.