Count Substrings That Can Be Rearranged to Contain a String I - Problem
You are given two strings word1 and word2. Your task is to find all substrings of word1 that can be rearranged to have word2 as a prefix.
A string x is called valid if we can rearrange the characters of x such that word2 appears at the beginning of the rearranged string.
For example: If word2 = "ab" and we have substring x = "bac", we can rearrange x to "abc", which has "ab" as a prefix, so x is valid.
Return the total number of valid substrings of word1.
Input & Output
example_1.py โ Basic Case
$
Input:
word1 = "abcabc", word2 = "ab"
โบ
Output:
10
๐ก Note:
Valid substrings are: "ab" (positions 0-1), "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). Each contains at least one 'a' and one 'b'.
example_2.py โ Single Character
$
Input:
word1 = "aaaa", word2 = "a"
โบ
Output:
10
๐ก Note:
All substrings of "aaaa" contain at least one 'a', so all 10 possible substrings are valid: "a" appears 4 times, "aa" appears 3 times, "aaa" appears 2 times, "aaaa" appears 1 time. Total: 4+3+2+1 = 10.
example_3.py โ No Valid Substrings
$
Input:
word1 = "xyz", word2 = "ab"
โบ
Output:
0
๐ก Note:
word1 contains no 'a' or 'b' characters, so no substring can be rearranged to have "ab" as a prefix.
Constraints
- 1 โค word2.length โค word1.length โค 104
- word1 and word2 consist only of lowercase English letters
- word2 is not empty
Visualization
Tap to expand
Understanding the Visualization
1
Position Window
Place window at starting position and begin expanding
2
Count Letters
Count frequency of each letter as window expands
3
Check Requirements
Verify if we have enough of each required letter
4
Count Valid Extensions
Once requirements met, all longer substrings are also valid
Key Takeaway
๐ฏ Key Insight: We don't need to actually rearrange strings - just check if character frequencies are sufficient!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code