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
Count Substrings: word1="bcda", word2="abc"Input String"bcda"Required Prefix"abc"Check all substrings for character requirements:"bcda" ✓"bcd" ✗"bc" ✗Requirements: a≥1, b≥1, c≥1"bcda" has a=1, b=1, c=1, d=1 ✓Result: 1 valid substring
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
Asked in
Google 35 Meta 28 Amazon 22
23.4K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen