Count Substrings That Can Be Rearranged to Contain a String I Problem
#3297
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3297.
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.
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^51 <= word2.length <= 10^4word1andword2consist only of lowercase English letters.
Solution
Approach: Sliding Window
A substring of word1 can be rearranged to have word2 as a prefix exactly when it contains at least as many of each letter as word2 does. Count the letters of word2, and let need be the number of letter types still lacking in the current window.
Move the right end r over word1, adding letters to the window. While the window [l, r] is valid (need == 0), shrink it from the left. When the loop stops, every start position before l gives a valid substring ending at r, so add l to the answer.
Complexity:
- Time complexity:
O(n + m) - Space complexity:
O(1), since the alphabet has26letters
from collections import Counter
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