Number of Substrings Containing All Three Characters

Given a string s consisting only of characters a, b and c.

Return the number of substrings containing at least one occurrence of all these characters a, b and c.

Example 1:

Input: s = "abcabc"
Output: 10
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again). 

Example 2:

Input: s = "aaacb"
Output: 3
Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb". 

Example 3:

Input: s = "abc"
Output: 1

Constraints:

  • 3 <= s.length <= 5 x 10^4

  • s only consists of a, b or c characters.

class Solution {
    public int numberOfSubstrings(String s) {
        int count[] = { 0, 0, 0 }, res = 0, i = 0, n = s.length();
        for (int j = 0; j < n; ++j) {
            ++count[s.charAt(j) - 'a'];
            // Compressing current window from left until one of the 3 (a,b,c) vanishes
            while (count[0] > 0 && count[1] > 0 && count[2] > 0)
                count[s.charAt(i++) - 'a']--;
            // now at this point we know that all the substrings from left side
            // ending at i-1 have atleast 1 (a,b,c)
            // therefore we can add all those subarrays
            res += i;
        }
        return res;
    }
}

Last updated