Count Valid Substrings I Problem
Description
LeetCode Problem 4102.
You are given a string s consisting only of the characters 'a', 'b', and 'c'.
A string is called valid if it does not contain "abc" as a substring.
Return the number of valid substrings in s. Substrings with different starting or ending indices are counted separately.
Example 1:
Input: s = "abac"
Output: 10
Explanation:
The following substrings don't contain "abc" as a substring:
- s[0..0] = "a"
- s[0..1] = "ab"
- s[0..2] = "aba"
- s[0..3] = "abac"
- s[1..1] = "b"
- s[1..2] = "ba"
- s[1..3] = "bac"
- s[2..2] = "a"
- s[2..3] = "ac"
- s[3..3] = "c"
Thus, the answer is 10.
Example 2:
Input: s = "abc"
Output: 5
Explanation:
The following substrings don't contain "abc" as a substring:
- s[0..0] = "a"
- s[0..1] = "ab"
- s[1..1] = "b"
- s[1..2] = "bc"
- s[2..2] = "c"
Thus, the answer is 5.
Example 3:
Input: s = "ac"
Output: 3
Explanation:
All substrings in s don't contain "abc" as a substring. Thus, the answer is 3.
Constraints:
1 <= s.length <= 10^5sonly consists of'a','b', and'c'characters.
Solution
Approach: Track the Latest "abc"
Count the substrings that end at each position j and add them up. A substring s[i..j] is invalid exactly when it contains an occurrence of "abc", that is, when i is at most the start of the latest occurrence that ends at or before j.
Keep last, the start index of that latest occurrence (-1 if there is none). Each time s[j-2..j] is "abc", set last = j - 2. The valid substrings ending at j are those with i > last, and there are j - last of them.
Complexity: O(n) time and O(1) space.
class Solution:
def countValidSubstrings(self, s: str) -> int:
ans = 0
last = -1 # start index of the latest "abc" that ends at or before j
for j in range(len(s)):
if j >= 2 and s[j - 2 : j + 1] == "abc":
last = j - 2
# substrings ending at j are valid exactly when they start after `last`
ans += j - last
return ans