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:

s = "aaabb", k = 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);
            counter.put(c, counter.get(c)+1);
            counter.put(c, 1);
    HashSet<Character> splitSet = new HashSet<Character>();
    for(char c: counter.keySet()){
        return s.length();
    int max = 0;
    int i=0, j=0;
        char c = s.charAt(j);
                max = Math.max(max, longestSubstring(s.substring(i, j), k));
         max = Math.max(max, longestSubstring(s.substring(i, j), k));
    return max;
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Mahak Goyal

    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).

  • saipabbathi

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

  • saipabbathi

    It sounds like a O(n) solution because only hash collections are used

  • sai sreenath

    time complexity of this solution please

  • Sravan Deepala

    what is the time complexity of this solution ?