Number of Substrings Containing All Three Characters

Pattern: Sliding window: variable size

medium

For each end position, every start up to the earliest of the last a, b and c gives a valid substring. Track those three last positions and add up the counts.

The problem

Given a string made only of the letters a, b and c, count the blocks of neighbouring characters that contain at least one of each letter. For example, "abcabc" has 10 such blocks, "aaacb" has 3 ("aaacb", "aacb" and "acb"), and "abc" has 1.

The function name numberOfSubstrings matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • Fix the end of a block at right. If the block starting at start contains all three letters, what about a block that starts earlier?
  • So for a fixed end, the valid starts form a range. Where does the range stop?
  • What single number per letter tells you where it stops?

Hints

    Brute force, and why it fails

    Check every block for all three letters: O(n²) blocks with a running set. The last-position method is O(n).

    The key insight

    Counting by end position turns the question into "how many starts work for this end?". The starts that work are exactly those up to the earliest of the three latest positions.

    Dry run

    a0 
    b1right
    c2 
    a3 
    b4 
    c5 
    lastA0
    lastB1
    lastC-1
    total0

    s = abcabc. last holds the latest index of a, b and c, and -1 means not seen yet. At index 0 and 1, c has not appeared, so nothing counts.

    Step 1 of 4

    The plan

    last = [-1, -1, -1]          # latest index of a, b, c
    total = 0
    for right from 0 to n - 1:
        last[s[right]] = right
        total = total + min(last) + 1
    return total
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    One pass with three stored positions.

    Edge cases

    • A letter missing from the whole string, as in "aaa": 0.
    • Exactly "abc" in any order: 1.
    • Long strings: the count grows like n²/2. Check the limits, and use a 64-bit count if n²/2 could pass 2³¹.
    I've built my logic, show the code

    Java

    class Solution {
        public int numberOfSubstrings(String s) {
            int[] last = {-1, -1, -1};              // latest index of 'a', 'b' and 'c'
            int total = 0;
            for (int right = 0; right < s.length(); right++) {
                last[s.charAt(right) - 'a'] = right;
                int earliest = Math.min(last[0], Math.min(last[1], last[2]));
                total += earliest + 1;              // every start from 0 to earliest gives a valid substring
            }
            return total;
        }
    }

    C++

    class Solution {
    public:
        int numberOfSubstrings(string s) {
            int last[3] = {-1, -1, -1};             // latest index of 'a', 'b' and 'c'
            int total = 0;
            for (int right = 0; right < static_cast<int>(s.size()); right++) {
                last[s[right] - 'a'] = right;
                int earliest = min(last[0], min(last[1], last[2]));
                total += earliest + 1;              // every start from 0 to earliest gives a valid substring
            }
            return total;
        }
    };

    Python

    class Solution:
        def numberOfSubstrings(self, s: str) -> int:
            last = [-1, -1, -1]                     # latest index of 'a', 'b' and 'c'
            total = 0
            for right, c in enumerate(s):
                last[ord(c) - 97] = right
                total += min(last) + 1              # every start from 0 to min(last) gives a valid substring
            return total

    Common mistakes

    • Counting only the shortest valid block for each end, instead of every valid start.
    • Forgetting the +1: starts 0 up to min(last) are min(last) + 1 starts.
    • Starting the three positions at 0 instead of -1, which counts blocks before a letter has even appeared.

    Similar problems