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
Sliding Window: Finding Valid RearrangementsInput: word1="bcaab", word2="ab"bcaabNeed: a=1, b=1Window: "bca"Has: a=1, b=1, c=1 โœ“Valid! +2 extensionsWindow: "caa"Has: a=2, c=1 โœ—Need b!Window: "aab"Has: a=2, b=1 โœ“Valid! +0 extensions๐Ÿ’ก Key insight: A substring is valid if it contains at least as many of each character as required by word23total valid substrings found
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!
Asked in
Google 45 Meta 32 Amazon 28 Microsoft 22
23.8K Views
Medium Frequency
~25 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