395. Longest Substring with At Least K Repeating Characters

395. Longest Substring with At Least K Repeating Characters

Description

Difficulty: Medium

Related Topics: Hash Table, String, Divide and Conquer, Sliding Window

Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is greater than or equal to k.

if no such substring exists, return 0.

Example 1:

1
2
3
Input: s = "aaabb", k = 3
Output: 3
Explanation: The longest substring is "aaa", as 'a' is repeated 3 times.

Example 2:

1
2
3
Input: s = "ababbc", k = 2
Output: 5
Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.

Constraints:

  • 1 <= s.length <= 104
  • s consists of only lowercase English letters.
  • 1 <= k <= 105

Hints/Notes

  • sliding window
  • need to introduce a new parameter distinct count and enumerate on it, without the parameter we don’t know how to shrink the subarray

Solution

Language: C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class Solution {
public:
    int longestSubstring(string s, int k) {
        int maxLen = 0;
        for (int i = 1; i <= 26; i++) {
            maxLen = max(maxLen, longest(s, k, i));
        }
        return maxLen;
    }

    int longest(string &s, int k, int count) {
        int left = 0, right = 0, currCount = 0, currValid = 0, maxLen = 0;
        vector<intfreq(260);
        while (right < s.size()) {
            if (freq[s[right] - 'a'] == 0) {
                currCount++;
            }
            freq[s[right] - 'a']++;
            if (freq[s[right] - 'a'] == k) {
                currValid++;
            }
            if (currCount == currValid) {
                maxLen = max(maxLen, right - left + 1);
            }
            while (left < right && currCount > count) {
                if (freq[s[left] - 'a'] == k) {
                    currValid--;
                }
                freq[s[left] -'a']--;
                if (freq[s[left] - 'a'] == 0) {
                    currCount--;
                }
                left++;
            }
            right++;
        }
        return maxLen;
    };
};