395. Longest Substring with At Least K Repeating Characters

This is a variation of the Sliding win template...!

T: O(26n)
S: O(1)
class Solution {
    // use typical sliding win is not working...so..
    public int longestSubstring(String s, int k) {
        int result = 0;
        for (int i = 1; i <= 26; i++) {
            result = Math.max(result, count(s, k, i));
        }
        return result;
    }
    // find sublen, "count" kind of char, and freq of each char >= k
    // so we can iterate 1 to 26 kind of char uniq char to find max sub len (and freq of each char  >= k)
    private int count(String s, int k, int count) {
        int[] freqCount = new int[26];
        int windowUniqCount = 0;
        int windowValidCount = 0;
        int result = 0;
        int left = 0;
        for (int right = 0; right < s.length(); right++) {
            char rightChar = s.charAt(right);
            if (freqCount[rightChar - 'a'] == 0) {
                windowUniqCount++;
            }
            freqCount[rightChar - 'a']++;
            if (freqCount[rightChar - 'a'] == k) {
                windowValidCount++;
            }
            while (left <= right && windowUniqCount > count) {
                char leftChar = s.charAt(left);
                if (freqCount[leftChar - 'a'] == k) {
                    windowValidCount--;
                }
                freqCount[leftChar - 'a']--;
                if (freqCount[leftChar - 'a'] == 0) {
                    windowUniqCount--;
                }
                left++;
            }
            if (windowValidCount == count) {
                result = Math.max(result, right - left + 1);
            }
        }
        return result;
    }
}
/**
T: O(26n)
S: O(1)
 */

Last updated