Count Substrings That Can Be Rearranged to Contain a String II - Problem
You are given two strings word1 and word2. Your task is to find the total number of valid substrings of word1.
A substring x is called valid if the characters in x can be rearranged to have word2 as a prefix. In other words, x must contain at least all the characters that appear in word2, with the same or greater frequency.
Example: If word2 = "abc", then substrings like "abcd", "bacde", or "xabcy" are valid because they can be rearranged to start with "abc".
Note: This problem has strict memory constraints, requiring a linear time complexity solution.
Input & Output
example_1.py — Basic Case
$
Input:
word1 = "bcca", word2 = "abc"
›
Output:
1
💡 Note:
Only the substring "bcc" (indices 0-2) contains at least 1 'a', 1 'b', and 1 'c', so it can be rearranged to have "abc" as prefix. Wait, that's wrong. Actually "bcca" contains a=1, b=1, c=2 which satisfies word2="abc" needing a=1,b=1,c=1. So the valid substrings are those containing at least these counts.
example_2.py — Multiple Valid Substrings
$
Input:
word1 = "abcabc", word2 = "ab"
›
Output:
10
💡 Note:
word2 needs a=1, b=1. Valid substrings: "ab"(0-1), "abc"(0-2), "abca"(0-3), "abcab"(0-4), "abcabc"(0-5), "abca"(1-4), "abcab"(1-5), "abcabc"(1-6), "ab"(3-4), "abc"(3-5). Total: 10 substrings.
example_3.py — No Valid Substrings
$
Input:
word1 = "a", word2 = "aa"
›
Output:
0
💡 Note:
word2 requires a=2, but word1 only has a=1 total. No substring of word1 can contain enough 'a' characters to satisfy the requirement.
Constraints
- 1 ≤ word1.length ≤ 105
- 1 ≤ word2.length ≤ 104
- word1 and word2 consist of lowercase English letters only
- Memory constraints are tighter than usual - linear time solution required
Visualization
Tap to expand
Understanding the Visualization
1
Set Recipe Requirements
Define what ingredients (characters) and quantities we need from word2
2
Slide Window Right
Expand window by moving right boundary, adding ingredients one by one
3
Check Recipe Complete
When window contains enough ingredients, count all valid recipe combinations
4
Count Efficiently
Use the insight that if [L,R] works, then [0,R], [1,R], etc. might also work
Key Takeaway
🎯 Key Insight: The sliding window technique transforms an O(n³) brute force problem into an elegant O(n) solution by avoiding redundant character counting and using the mathematical property that valid window extensions are also valid.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code