Number of Substrings Containing All Three Characters
Count the substrings of a string of a, b and c that contain all three letters, in one pass.
Given a string ss
Example 1
Output: 10
Example 2
Output: 3
Explanation: "aaacb", "aacb" and "acb".
The Idea
Picture the string "abcabc" written on a strip of paper. A substring is any piece you can cut out with two snips: "bca", "cab", or the whole strip. There are 21 such pieces, 6 of length one, 5 of length two, and so on down to the whole strip. Ten of them contain an a, a b and a c.
Checking the pieces one by one works for six characters, but the number of pieces grows with the square of the length. A string of 50,000 characters has 1,250,025,000 of them. So how can we count the pieces that have all three letters without looking at each one?
Group the pieces by where they end. Positions count from 0, so position 4 is the second b. Look at the picture below: it lists every piece that ends at position 4.
The end position is marked right = 4
Notice the order. Moving the start one step to the left only adds a character to the piece, so the piece can never lose a letter. Once some start works, every start to its left works too. The valid starts always form one block beginning at 0.
Call the first start that fails leftleft = 3leftleft
Solution Approach
Turning that idea into code means settling three things: how to find left
Finding left for each end
How do we find leftleftrightrightleftleft
That check repeats until the stretch is missing a letter. The start where it stops is the first start that fails, which is the new left
Telling that a letter is missing
How do we know whether the window holds a, b and c, without reading it again? Keep an array counts.charAt(i) - 'a'
Keeping the pass fast
Could leftleftleft
The count itself can be large. It can never exceed n(n + 1)/2, the number of all substrings, and a Java intresultlong
Java Solution
The method numberOfSubstrings
- First, create the array
with three slots for the a's, b's and c's in the window. Setcount , the window's start, andleft , the running answer, to 0.result - A
loop movesfor from the first character to the last. At each step it addsright to the window withs.charAt(right) .count[s.charAt(right) - 'a']++ - Inside, a
loop runs as long as all three slots ofwhile are above 0. Each time, it removescount froms.charAt(left) and movescount one step forward.left - When the
loop stops, the starts 0 towhile are valid for thisleft - 1 , so addright toleft .result - After the
loop, returnfor .result
The main
public class NumberOfSubstringsContainingAllThreeCharacters {
public static int numberOfSubstrings(String s) {
int[] count = new int[3]; // counts of a, b, c in s[left..right]
int left = 0;
int result = 0;
for (int right = 0; right < s.length(); right++) {
count[s.charAt(right) - 'a']++;
while (count[0] > 0 && count[1] > 0 && count[2] > 0) {
count[s.charAt(left) - 'a']--;
left++; // shrink until one letter is missing
}
result += left; // starts 0 .. left-1 all contain a, b and c
}
return result;
}
public static void main(String[] args) {
System.out.println(numberOfSubstrings("abcabc"));
System.out.println(numberOfSubstrings("aaacb"));
System.out.println(numberOfSubstrings("abc"));
System.out.println(numberOfSubstrings("aabbaa"));
System.out.println(numberOfSubstrings("cccbbbaaa"));
}
}
Running it prints:
10
3
1
0
9
"abcabc" gives 10 and "aaacb" gives 3, matching the examples. "abc" gives 1, since only the whole string has all three letters. "aabbaa" gives 0: no window ever holds a c, so the whileleft
Look at the last line, 9. A valid piece of "cccbbbaaa" must start at one of the three c's, cross all the b's and end at one of the three a's, and 3 × 3 = 9.
The whileifleftleft
Complexity
The work is one pass of rightleft
- Time: O(n), because
visits each of the n characters once andright only moves forward, so theleft loop removes at most n characters over the whole run.while - Space: O(1), because
always has three slots, one each for a, b and c, plus the integerscount ,left andright , however long the string is.result
The same counting step, adding left