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
Input: s = "aabaaab", k = 2
Output: 7
Explanation: The entire string "aabaaab" has exactly 2 unique characters 'a' and 'b',
making it the longest valid substring.
π 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
cnt
to count distinct characters andmaxi
to store the result.
Expand Window:
Move
j
pointer and increment frequency ofs[j]
.If this is the first occurrence of
s[j]
(frequency was 0), incrementcnt
.
Contract Window:
If
cnt
exceedsk
(more than k distinct characters), shrink window from left.Decrement frequency of
s[i]
and if it becomes 0, decrementcnt
.Move
i
pointer forward.
Update Result:
Only when
cnt == k
(exactly k distinct characters), updatemaxi
with current window size.
Return Result:
Return
maxi
if 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++)
class Solution {
public:
int longestKSubstr(string &s, int k) {
int n = s.size(), i = 0, cnt = 0, maxi = -1;
vector<int> fre(26, 0);
for (int j = 0; j < n; j++) {
if (fre[s[j] - 'a']++ == 0) cnt++;
while (cnt > k) {
if (--fre[s[i] - 'a'] == 0) cnt--;
i++;
}
if (cnt == k) maxi = max(maxi, j - i + 1);
}
return maxi;
}
};
π§βπ» Code (Java)
class Solution {
public int longestKSubstr(String s, int k) {
int[] freq = new int[26];
int i = 0, cnt = 0, max = -1;
for (int j = 0; j < s.length(); j++) {
if (freq[s.charAt(j) - 'a']++ == 0) cnt++;
while (cnt > k) {
if (--freq[s.charAt(i) - 'a'] == 0) cnt--;
i++;
}
if (cnt == k) max = Math.max(max, j - i + 1);
}
return max;
}
}
π Code (Python)
class Solution:
def longestKSubstr(self, s, k):
freq = [0] * 26
i = cnt = maxi = 0
for j in range(len(s)):
if freq[ord(s[j]) - ord('a')] == 0:
cnt += 1
freq[ord(s[j]) - ord('a')] += 1
while cnt > k:
freq[ord(s[i]) - ord('a')] -= 1
if freq[ord(s[i]) - ord('a')] == 0:
cnt -= 1
i += 1
if cnt == k:
maxi = max(maxi, j - i + 1)
return maxi if maxi > 0 else -1
π§ 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