26. Longest K unique characters substring
The problem can be found at the following link: Question Link
My Approach
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
andj
.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
exceededk
, I moved the startingi
pointer to shrink the window and maintain at mostk
unique characters.I updated the
out
variable wheneverc
became equal tok
to keep track of the longest valid substring.
Explanation with example
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 and Auxiliary Space Complexity
Time Complexity: The code runs in
O(N)
time, whereN
is the length of the input strings
. This is because both thei
andj
pointers traverse the string once.Auxiliary Space Complexity: The code uses an unordered_map
cnt
to store character frequencies, which can have at mostK
unique characters. Therefore, the space complexity isO(K)
.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. 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 getlost01/gfg-potd repository.
Last updated