2
https://leetcode.com/problems/longest-substring-with-at-least-k-repeating-characters/7
At a glance even though it seems like it can be solved with sliding window,8
it's hard to come up with window condition with the traditional sliding9
window approach. Problem is what will be your valid window criteria? Since we10
dont know how many unique chars might come up in the window, we dont know11
whether we should shrink the window or even though few of the unique chars12
have at least k instances.14
So we change the problem a bit. We change the window criteria:15
Find the max length window with atmost X unique chars. This is easier16
problem to deal with. The shrinking window criteria is clear, also we also17
keep track of chars in the window with frequency >= k while solving this20
Now since we are limiting the no. of unique chars, we need to run the above21
|unique chars in s| times.25
int uniqueChars(string &s) {26
unordered_set<char> chars(s.begin(), s.end());30
int longestSubstring(string s, int k) {31
// find the no. of unique chars in string32
int max_unique_chars = uniqueChars(s);33
int max_len = 0, n = s.size();35
for (int curr_unique_chars = 1; curr_unique_chars <= max_unique_chars; curr_unique_chars++) {36
int start = 0, end = 0;38
unordered_map<char, int> freq;40
// Process the max length window with at max curr_unique_chars unique43
// attempt window expansion44
if (++freq[s[end]] == k) ++atleast_k;47
// shrink the window if unique chars exceeds the limit48
while (freq.size() > curr_unique_chars && start <= end) {49
// Current char contributed to atleast_k count, so it's count will be51
if (freq[s[start]] == k) --atleast_k;52
if (--freq[s[start]] == 0) freq.erase(s[start]);55
// If the current window has required no. of chars and it also each56
// unique chars have atleast k instances57
if (freq.size() == curr_unique_chars && atleast_k == freq.size())58
max_len = max(max_len, end - start);