Count Substrings That Can Be Rearranged to Contain a String II Problem
Description
LeetCode Problem 3298.
You are given two strings word1 and word2.
A string x is called valid if x can be rearranged to have word2 as a prefix.
Return the total number of valid substrings of word1.
Note that the memory limits in this problem are smaller than usual, so you must implement a solution with a linear runtime complexity.
Example 1:
Input: word1 = "bcca", word2 = "abc"
Output: 1
Explanation:
The only valid substring is "bcca" which can be rearranged to "abcc" having "abc" as a prefix.
Example 2:
Input: word1 = "abcabc", word2 = "abc"
Output: 10
Explanation:
All the substrings except substrings of size 1 and size 2 are valid.
Example 3:
Input: word1 = "abcabc", word2 = "aaabc"
Output: 0
Constraints:
1 <= word1.length <= 10^61 <= word2.length <= 10^4word1andword2consist only of lowercase English letters.
Solution
Approach: Sliding Window
We need to count the substrings of word1 that contain every letter of word2 with at least the required multiplicity, since a substring can be rearranged to start with word2 exactly when that holds. If word1 is shorter than word2, the answer is 0.
Count the letters of word2 in an array cnt of size 26, and let need be the number of distinct letters whose requirement is not yet met. Sweep the right end over word1, keeping the letter counts of the window in win. When adding a character makes win[c] reach cnt[c], one requirement is satisfied and need drops by one.
While need is 0, the window is valid, so move the left end forward: if removing word1[l] brings its count below the requirement, need goes back up. When the loop stops, every start before l gives a valid substring ending at the current position, so add l to the answer.
Complexity: O(n + m) time and O(1) space (26 letters), where n and m are the lengths of word1 and word2.
class Solution:
def validSubstringCount(self, word1: str, word2: str) -> int:
if len(word1) < len(word2):
return 0
cnt = Counter(word2)
need = len(cnt)
ans = l = 0
win = Counter()
for c in word1:
win[c] += 1
if win[c] == cnt[c]:
need -= 1
while need == 0:
if win[word1[l]] == cnt[word1[l]]:
need += 1
win[word1[l]] -= 1
l += 1
ans += l
return ans