03. Longest Substring with K Uniques
β GFG solution to the Longest Substring with K Uniques problem: find maximum length substring containing exactly k distinct characters using sliding window technique. π
The problem can be found at the following link: π Question Link
π§© Problem Description
You are given a string s consisting only lowercase alphabets and an integer k. Your task is to find the length of the longest substring that contains exactly k distinct characters.
Note: If no such substring exists, return -1.
π Examples
Example 1
Input: s = "aabacbebebe", k = 3
Output: 7
Explanation: The longest substring with exactly 3 distinct characters is "cbebebe",
which includes 'c', 'b', and 'e'.Example 2
Input: s = "aaaa", k = 2
Output: -1
Explanation: There's no substring with 2 distinct characters.Example 3
π Constraints
$1 \le \text{s.size()} \le 10^5$
$1 \le k \le 26$
β
My Approach
The optimal approach uses the Sliding Window technique with a Frequency Array to efficiently track distinct characters and their frequencies:
Sliding Window + Frequency Array
Initialize Variables:
Use two pointers:
i(start of window) andj(end of window).Maintain a frequency array
fre[26]to store frequency of each character in current window.Track
cntto count distinct characters andmaxito store the result.
Expand Window:
Move
jpointer and increment frequency ofs[j].If this is the first occurrence of
s[j](frequency was 0), incrementcnt.
Contract Window:
If
cntexceedsk(more than k distinct characters), shrink window from left.Decrement frequency of
s[i]and if it becomes 0, decrementcnt.Move
ipointer forward.
Update Result:
Only when
cnt == k(exactly k distinct characters), updatemaxiwith current window size.
Return Result:
Return
maxiif found, otherwise return -1.
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where n is the length of the string. Each character is visited at most twice (once by right pointer and once by left pointer).
Expected Auxiliary Space Complexity: O(1), as we use a fixed-size frequency array of 26 elements for lowercase alphabets, which is constant space.
π§βπ» Code (C++)
π§βπ» Code (Java)
π Code (Python)
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated