Longest Substring with At Least K Repeating Characters

Find the longest piece of a string in which every letter appears at least k times.

Given a string s of lowercase letters and an integer k, return the length of the longest substring in which every letter appears at least k times. A substring is a run of neighbouring characters, such as "bab" in "ababbc". If no substring qualifies, return 0.

Example 1
Input: s = "aaabb", k = 3
Output: 3
Explanation: "aaa": a appears 3 times.
Example 2
Input: s = "ababbc", k = 2
Output: 5
Explanation: "ababb": a appears 2 times and b appears 3 times.
Solution

The Idea

Picture a row of letter tiles: a, a, a, b, b. You may keep any run of neighbouring tiles, but each letter in the run must show up at least 3 times. The run "aaa" works. The whole row does not, because b shows up only twice, and no run can hold more b's than the whole row has. So the best run is "aaa", of length 3.

The reasoning about b works for any string. In Example 2, "ababbc" with k = 2, the letter c appears once in the whole string, so no substring can hold it twice. The answer cannot contain c at all, and c acts like a wall: the answer lies wholly on one side of it. Call a letter that appears fewer than k times a rare letter.

Cutting at c leaves "ababb", where a appears 2 times and b 3 times. No letter is rare there, so the whole part is valid and the answer is 5. Does one cut always finish the job? Take a longer string, "ababbbcadd", with k = 3, and look at the picture below.

The string ababbbcadd with k = 3 is cut at c and d, which appear fewer than 3 times, leaving ababbb and a. In ababbb, a now appears only twice, so it is cut at each a, leaving b and bbb. The part bbb is valid and has length 3.

In the row labelled "the whole string", a appears 3 times, b 4 times, c once and d twice. So c and d are rare, and cutting at them leaves "ababbb" and a lone "a", shown in the row labelled "parts after the first cut". The lone "a" is shorter than 3 letters, so it cannot hold any letter 3 times.

Now count again inside "ababbb". One of the three a's was left behind in the other part, so a appears only twice here. A letter that was fine in the whole string has become rare inside a part. Cutting at both a's leaves "b" and "bbb", in the row labelled "parts after the second cut". In "bbb", b appears 3 times, so no letter is rare and the answer is 3.

So the same step repeats at every size: count the letters of a piece, cut at each rare letter, and do the same to every smaller piece. A piece with no rare letter is valid as a whole. Solving a problem by splitting it into smaller problems of the same kind is called divide and conquer, and a method that calls itself on the smaller pieces is called recursive.

Solution Approach

Turning that idea into code means settling three things: how to count the letters of a piece, where to cut it, and when a piece needs no more cutting. Two simpler searches show why the cutting is worth it.

Counting the letters of a piece

How do we know which letters are rare in a piece? The string holds only the 26 lowercase letters, so an array of 26 counters is enough. The letter a goes to counter 0, b to counter 1, and so on, which s.charAt(i) - 'a' works out. One pass over the piece fills the array.

A piece does not need to be copied into a new string. Two positions, where it starts and where it ends, describe it fully, and every call reads the same s.

Cutting at every rare letter

Where exactly do we cut? The picture cut at all the rare letters of a piece at once, and the code does the same. A second pass over the piece remembers where the current part began. Each time it meets a rare letter, it solves the part that just ended and starts a new part right after the letter.

When the pass reaches the end of the piece, one part is still open: the text after the last rare letter. It needs one more call of its own, or an answer sitting at the end of a piece would be missed.

When a piece needs no more cutting

When does the cutting stop? A piece shorter than k cannot hold any letter k times, so its answer is 0 without counting anything. A piece with no rare letter is valid as it stands, so its answer is its own length. Every cut makes the pieces smaller, so one of these two always happens in the end.

Simpler searches and why they are slow

Why not check every substring? A string of 10,000 letters has about 50 million substrings, and each one needs its letter counts checked. Cutting never looks at a substring that contains a rare letter.

Why not a sliding window, the usual tool for finding a longest substring? A sliding window is a stretch of the string between two markers that only move right: the right one adds letters, and the left one drops letters when the stretch breaks a rule. That works when adding a letter can only break the rule.

Here, adding a letter can break or fix it. With k = 2, adding a b to "aab" fixes the b's, while adding a c to "aabb" brings in a letter that appears once. So the window cannot tell when to drop letters from the left.

An optional sliding-window version

A sliding window can still solve the problem with one extra rule. For each number u from 1 to 26, slide a window that may hold at most u different letters, and record its length whenever all of them appear at least k times. Now adding a letter can only break the rule "at most u different letters", so the window knows when to shrink. The cutting version below is shorter and just as fast.

Java Solution

The method longestSubstring works in these steps:

  1. First, hand the whole string to the helper longest(s, 0, s.length(), k). It works on the piece from position start up to, but not including, end.
  2. If the piece is shorter than k, that is end - start < k, return 0.
  3. Count the letters of the piece into count, an array of 26 counters.
  4. Scan the piece again with i. partStart marks where the current part begins, best holds the longest answer found so far, and the flag split, which starts false, records whether any cut was made. When the letter at i is rare, solve the part from partStart up to i with a recursive call, keep the larger of that and best, move partStart to i + 1 and set split to true.
  5. If split is still false, no letter was rare and the whole piece is valid: return its length.
  6. Otherwise solve the part after the last rare letter with one more call, and return the larger of that and best.

The main method runs both examples, the string from the picture, a string whose answer sits at the end, a string with no valid substring, k = 1, and the empty string.

Java
public class LongestSubstringWithAtleastKRepeatingChars {

    public static int longestSubstring(String s, int k) {
        return longest(s, 0, s.length(), k);
    }

    // Longest valid substring inside s[start .. end-1]
    private static int longest(String s, int start, int end, int k) {
        if (end - start < k) {
            return 0;                         // too short to hold any letter k times
        }
        int[] count = new int[26];
        for (int i = start; i < end; i++) {
            count[s.charAt(i) - 'a']++;
        }
        int best = 0;
        int partStart = start;
        boolean split = false;
        for (int i = start; i < end; i++) {
            if (count[s.charAt(i) - 'a'] < k) {
                // this letter can never be in the answer: solve the part before it
                best = Math.max(best, longest(s, partStart, i, k));
                partStart = i + 1;
                split = true;
            }
        }
        if (!split) {
            return end - start;               // every letter appears at least k times
        }
        return Math.max(best, longest(s, partStart, end, k));   // the part after the last cut
    }

    static void run(String s, int k) {
        System.out.println("\"" + s + "\", k = " + k + " -> " + longestSubstring(s, k));
    }

    public static void main(String[] args) {
        run("aaabb", 3);
        run("ababbc", 2);
        run("ababbbcadd", 3);
        run("bbaaa", 3);
        run("abcab", 2);
        run("abc", 1);
        run("", 1);
    }
}

Running it prints:

Output
"aaabb", k = 3 -> 3
"ababbc", k = 2 -> 5
"ababbbcadd", k = 3 -> 3
"bbaaa", k = 3 -> 3
"abcab", k = 2 -> 0
"abc", k = 1 -> 3
"", k = 1 -> 0

The line for "ababbbcadd" gives 3, the "bbb" from the last row of the picture. Look at the line for "bbaaa": its answer, "aaa", comes after the last rare letter, the second b, so only the final call in step 6 finds it. A version that returns best straight after the loop prints 0 for this line, and 0 for "ababbbcadd" too, where "bbb" also ends its piece.

The line for "abcab" shows why the counting must be repeated. In the whole string, a and b each appear twice, which looks fine for k = 2. But c cuts the string into "ab" and "ab", and in each of them every letter appears once. With k = 1, no letter can be rare, so "abc" is valid as a whole and gives 3. The empty string is shorter than k and gives 0.

The original implementation, LongestSubstringWithAtleastKRepeatingChars.java, is on GitHub.

Complexity

The work is counting and scanning the pieces, repeated at every level of cutting.

  • Time: O(26 × n), which is O(n), where n is the length of s. The pieces at one level of cutting do not overlap, so counting and scanning all of them takes at most about 2n steps. A part never contains the rare letters it was cut at, so each level has at least one letter fewer than the level above, and there are at most 26 levels.
  • Space: O(1) besides the input. Because there are at most 26 levels of cutting, at most about 27 calls wait on the stack at once, each with its own 26 counters. Pieces are pairs of positions in s, never copies.

The optional version slides a plain window 26 times. Sliding Window Basics explains how such a window moves.