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 skk
Example 1
Output: 3
Explanation: "aaa": a appears 3 times.
Example 2
Output: 5
Explanation: "ababb": a appears 2 times and b appears 3 times.
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 = 2k
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
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'
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 kk
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
An optional sliding-window version
A sliding window can still solve the problem with one extra rule. For each number uuku
Java Solution
The method longestSubstring
- First, hand the whole string to the helper
. It works on the piece from positionlongest(s, 0, s.length(), k) up to, but not including,start .end - If the piece is shorter than
, that isk , return 0.end - start < k - Count the letters of the piece into
, an array of 26 counters.count - Scan the piece again with
.i marks where the current part begins,partStart holds the longest answer found so far, and the flagbest , which starts false, records whether any cut was made. When the letter atsplit is rare, solve the part fromi up topartStart with a recursive call, keep the larger of that andi , movebest topartStart and seti + 1 to true.split - If
is still false, no letter was rare and the whole piece is valid: return its length.split - Otherwise solve the part after the last rare letter with one more call, and return the larger of that and
.best
The maink = 1
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:
"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
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 = 2k = 1k
The original implementation,
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
. 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.s - 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
, never copies.s
The optional version slides a plain window 26 times.