17.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

Solution: (Sliding Window)

Finding Lower bound of each letter and calculating the number of substrings

class Solution
{
public:
    int numberOfSubstrings(string s)
    {

        vector<int> v{-1, -1, -1};

        int res = 0;

        for (int i = 0; i < s.length(); i++)
        {
            v[s[i] - 97] = i;

            res = res + 1 + min(v[0], min(v[1], v[2]));
        }

        return res;
    }
};

Time Complexity: O(n)

Last updated