Count Substrings That Can Be Rearranged to Contain a String II - Problem
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.
Input & Output
Example 1 — Basic Valid Substring
$
Input:
word1 = "bcda", word2 = "abc"
›
Output:
1
💡 Note:
The substring "bcda" contains all characters needed (a=1, b=1, c=1) to rearrange and have "abc" as prefix. Only 1 valid substring exists.
Example 2 — Multiple Valid Substrings
$
Input:
word1 = "abcabc", word2 = "ab"
›
Output:
10
💡 Note:
Many substrings contain at least 1 'a' and 1 'b': "ab", "abc", "abca", "abcab", "abcabc", "bc"+next chars, etc. Total count is 10.
Example 3 — No Valid Substrings
$
Input:
word1 = "xyz", word2 = "abc"
›
Output:
0
💡 Note:
No substring of "xyz" contains the required characters a, b, c to form "abc" as prefix.
Constraints
- 1 ≤ word2.length ≤ word1.length ≤ 105
- word1 and word2 consist of lowercase English letters only
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
word1 provides characters, word2 defines requirements
2
Substring Validation
Check if substring can be rearranged to have word2 as prefix
3
Count Result
Sum all valid substrings
Key Takeaway
🎯 Key Insight: A substring is valid if it contains at least as many of each character as required by word2
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code