Number of Substrings Containing All Three Characters

Similar Problems:

- CheatSheet: LeetCode For Code Interview
- CheatSheet: Common Code Problems & Follow-ups
- Tag: #slidingwindow

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.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

- Solution:

## https://code.dennyzhang.com/number-of-substrings-containing-all-three-characters ## Basic Ideas: sliding window ## ## Check all the starting positions ## ## Complexity: Time O(n), Space O(1) class Solution: def numberOfSubstrings(self, s: str) -> int: res = 0 counts = [0]*3 n = len(s) j = 0 for i in range(0, n-2): # remove left if i>0: counts[ord(s[i-1])-ord('a')] -= 1 # keep moving right while j<n: if counts[0]>0 and counts[1]>0 and counts[2]>0: break counts[ord(s[j])-ord('a')] += 1 j += 1 # collect result if counts[0]>0 and counts[1]>0 and counts[2]>0: res += n-j+1 return res