Count Substrings That Can Be Rearranged to Contain a String I - 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.
Input & Output
Example 1 — Basic Case
$
Input:
word1 = "bcca", word2 = "abc"
›
Output:
1
💡 Note:
Only one valid substring "bcc" at index 0-2. It can be rearranged as "bcc" → "abc" + "c" (abc as prefix)
Example 2 — Multiple Valid Substrings
$
Input:
word1 = "abcabc", word2 = "abc"
›
Output:
10
💡 Note:
Valid substrings: "abc"(0-2), "abca"(0-3), "abcab"(0-4), "abcabc"(0-5), "bca"(1-3), "bcab"(1-4), "bcabc"(1-5), "cab"(2-4), "cabc"(2-5), "abc"(3-5)
Example 3 — No Valid Substrings
$
Input:
word1 = "abcab", word2 = "abc"
›
Output:
7
💡 Note:
word1 has enough characters for abc. Valid substrings include "abc"(0-2), "abca"(0-3), "abcab"(0-4), "bca"(1-3), "bcab"(1-4), "cab"(2-4)
Constraints
- 1 ≤ word2.length ≤ word1.length ≤ 104
- word1 and word2 consist only of lowercase English letters
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
word1="bcca", word2="abc" needs a≥1, b≥1, c≥1
2
Check Substrings
Examine each substring's character frequencies
3
Count Valid
Count substrings that can rearrange to have word2 as prefix
Key Takeaway
🎯 Key Insight: A substring is valid if its character frequencies meet or exceed word2's requirements
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code