LeetCode – Longest Substring with At Least K Repeating Characters (Java)

Find the length of the longest substring T of a given string (consists of lowercase letters only) such that every character in T appears no less than k times.

Example 1:

Input:
s = "aaabb", k = 3

Output:
3
The longest substring is "aaa", as 'a' is repeated 3 times.

Java Solution

This problem can be solved using DFS. When all chars in the input string occurs >=k, return the length. But we first need to split the input string by using the characters whose occurrence < k.

public int longestSubstring(String s, int k) {
    HashMap<Character, Integer> counter = new HashMap<Character, Integer>();
 
    for(int i=0; i<s.length(); i++){
 
        char c = s.charAt(i);
        if(counter.containsKey(c)){
            counter.put(c, counter.get(c)+1);
        }else{
            counter.put(c, 1);
        }
 
    }
 
    HashSet<Character> splitSet = new HashSet<Character>();
    for(char c: counter.keySet()){
        if(counter.get(c)<k){
            splitSet.add(c);
        }
    }
 
    if(splitSet.isEmpty()){
        return s.length();
    }
 
    int max = 0;
    int i=0, j=0;
    while(j<s.length()){
        char c = s.charAt(j);
        if(splitSet.contains(c)){
            if(j!=i){
                max = Math.max(max, longestSubstring(s.substring(i, j), k));
            }
            i=j+1;
        }
        j++;
    }
 
    if(i!=j)
         max = Math.max(max, longestSubstring(s.substring(i, j), k));
 
    return max;
}

5 thoughts on “LeetCode – Longest Substring with At Least K Repeating Characters (Java)”

  1. I think it should be o(n^2), because every time we found a char of count less than desired frequency k, we will discard that char and recuse for substring left to it and another recursion for right to it. So lets say in one iteration(or first call to recursion we left 1 char and traverse n-1 chars), in next we will again leave 1 char if its freq less than k, and do recursion again for (n-2) chars and so on till only 1 char is left (worst case).
    So , complexity should be n + (n-1) + (n-2) + …… 1 = O(n^2).

  2. This can be done by just isn’t hashmap. Instead if storing in the hashset, remove the element from hash map

Leave a Comment