Count Valid Substrings II Problem
Description
LeetCode Problem 4104.
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 subsequence.
Return the number of valid substrings in s. Substrings with different starting or ending indices are counted separately.
Example 1:
Input: s = "abac"
Output: 9
Explanation:
The following substrings don't contain "abc" as a subsequence:
- s[0..0] = "a"
- s[0..1] = "ab"
- s[0..2] = "aba"
- 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 9.
Example 2:
Input: s = "abc"
Output: 5
Explanation:
The following substrings don't contain "abc" as a subsequence:
- 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 subsequence. Thus, the answer is 3.
Constraints:
1 <= s.length <= 10^5sonly consists of'a','b', and'c'characters.
Solution
Approach: Next Occurrence Tables
For each start i, find the shortest substring s[i..r] that contains "abc" as a subsequence. Then s[i..j] is valid for every j < r, which gives r - i valid substrings (use r = n if there is no such substring).
Matching "abc" greedily from i finds the earliest end: take the first a at or after i, then the first b after it, then the first c after that. Precompute nxt[c][i], the first index at or after i holding letter c (or n), by scanning from the right. Then each start takes three lookups.
Complexity: O(n) time and O(n) space.
class Solution:
def countValidSubstrings(self, s: str) -> int:
n = len(s)
# nxt[c][i]: first index >= i holding the letter c, or n if there is none
nxt = [[n] * (n + 1) for _ in range(3)]
for i in range(n - 1, -1, -1):
for c in range(3):
nxt[c][i] = nxt[c][i + 1]
nxt[ord(s[i]) - ord("a")][i] = i
ans = 0
for i in range(n):
# greedily match "abc" as early as possible; r is where the match ends
a = nxt[0][i]
b = nxt[1][a + 1] if a < n else n
r = nxt[2][b + 1] if b < n else n
# s[i..j] is valid for every j < r
ans += r - i
return ans