Number of Substrings Containing All Three Characters Problem
Description
LeetCode Problem 1358.
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^4sonly consists of'a','b'or'c'characters.
Solution
Approach: Count by Right End Using Last Positions
Checking every substring is O(n2) and too slow for 5 * 104 characters. Instead, count the good substrings by where they end.
Fix the right end i. A substring s[j..i] contains all three letters exactly when each of a, b and c appears somewhere in j..i, that is, when j is at most the last position of each letter up to i. So with last[a], last[b], last[c] being those last positions (or -1 if the letter has not appeared yet), every start j from 0 to min(last) works, which is min(last) + 1 substrings. If some letter is still missing, min(last) is -1 and that adds 0.
Walk through the string once, update last for the current letter, and add min(last) + 1.
For "aaacb", the counts added at each end are 0, 0, 0, 0 and then min(2, 4, 3) + 1 = 3 at the final b: the substrings starting at index 0, 1 or 2.
The total is at most n(n+1)/2, about 1.25 * 109 for the largest input, which still fits in a 32-bit int.
Complexity: O(n) time and O(1) extra space.
class Solution:
def numberOfSubstrings(self, s: str) -> int:
last = {"a": -1, "b": -1, "c": -1} # last index of each letter so far
ans = 0
for i, ch in enumerate(s):
last[ch] = i
# Substrings ending at i that start at 0..min(last) contain all three letters.
ans += min(last.values()) + 1
return ans