DDSA
Advertisement

1358. Number of Substrings Containing All Three Characters

Time: O(n)
Space: O(1)

Approach

Sliding window; shrink left while all three characters are present; every valid window contributes 'l' substrings for each right position.

1358.cs
C#
// Approach: Sliding window; shrink left while all three characters are present; every valid window contributes 'l' substrings for each right position.
// Time: O(n) Space: O(1)

public class Solution
{
    public int NumberOfSubstrings(string s)
    {
        int ans = 0;
        int[] count = new int[3];

        int l = 0;
        foreach (char c in s)
        {
            ++count[c - 'a'];
            while (count[0] > 0 && count[1] > 0 && count[2] > 0)
                --count[s[l++] - 'a'];
            // s[0..r], s[1..r], ..., s[l - 1..r] are satisfied strings.
            ans += l;
        }

        return ans;
    }
}
Advertisement
Was this solution helpful?