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 s made only of the letters a, b and c, return how many substrings of s contain each of the three letters at least once. A substring is a run of characters that sit next to each other: "bca" is a substring of "abcabc", but "acb" is not. A substring that appears at two different places is counted twice.

Example 1
Input: s = "abcabc"
Output: 10
Example 2
Input: s = "aaacb"
Output: 3
Explanation: "aaacb", "aacb" and "acb".
Solution

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 string abcabc with right at position 4. The substrings ending there start at 0 to 4: abcab, bcab and cab have a, b and c; ab and b have no c. The valid starts are 0, 1 and 2, and left = 3 is the first start missing a letter.

The end position is marked right = 4. The row labelled start 0 is the piece "abcab", start 1 is "bcab" and start 2 is "cab". All three have a, b and c. The rows for start 3 and start 4 hold "ab" and "b", and neither has a c.

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 left. In the picture left = 3, and the valid starts 0, 1 and 2 are exactly 3 pieces. So for each end position we need only one number, left, and the answer is the sum of left over all end positions.

Solution Approach

Turning that idea into code means settling three things: how to find left for each end, how to tell that a letter is missing, and how to keep the whole pass fast.

Finding left for each end

How do we find left without testing every start again? Look at the stretch of characters from left to right. When right moves one step, its new character joins the stretch. If the stretch now holds all three letters, then left is a valid start after all, so left moves one step forward and drops its character.

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. A stretch whose two edges move forward along the data like this is called a sliding window.

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 count with three slots, the number of a's, b's and c's in the window. The expression s.charAt(i) - 'a' turns a, b and c into the slots 0, 1 and 2. A character joining or leaving the window changes one slot, and the window has all three letters when all three slots are above 0.

Keeping the pass fast

Could left ever need to move back? No. Every start before left was valid for the previous end, and adding one more character on the right cannot take a letter away. So left carries on from where it stopped. Each character joins the window once and leaves it at most once, about 2n steps for a string of n characters.

The count itself can be large. It can never exceed n(n + 1)/2, the number of all substrings, and a Java int holds that for strings of up to 65,535 characters. For longer strings, make result a long.

Java Solution

The method numberOfSubstrings works in these steps:

  1. First, create the array count with three slots for the a's, b's and c's in the window. Set left, the window's start, and result, the running answer, to 0.
  2. A for loop moves right from the first character to the last. At each step it adds s.charAt(right) to the window with count[s.charAt(right) - 'a']++.
  3. Inside, a while loop runs as long as all three slots of count are above 0. Each time, it removes s.charAt(left) from count and moves left one step forward.
  4. When the while loop stops, the starts 0 to left - 1 are valid for this right, so add left to result.
  5. After the for loop, return result.

The main method runs both examples, the shortest string that counts, "abc", a string with no c, "aabbaa", and "cccbbbaaa", where each letter comes in one block.

Java
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:

Output
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 while loop never runs and left stays at 0.

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 while loop matters here. With an if in its place, left moves at most one step per character and falls behind. That version returns 1 for "aaacb" instead of 3, because at the final b it moves left past only the first a. For "cccbbbaaa" it returns 6 instead of 9.

Complexity

The work is one pass of right over the string, plus the steps of left.

  • Time: O(n), because right visits each of the n characters once and left only moves forward, so the while loop removes at most n characters over the whole run.
  • Space: O(1), because count always has three slots, one each for a, b and c, plus the integers left, right and result, however long the string is.

The same counting step, adding left for every right end, solves Count Subarrays Where Max Element Appears at Least K Times.