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 Valid Substrings INPUT word1 = "bcda" b c d a Index: 0 1 2 3 word2 = "abc" a b c Required chars: a:1, b:1, c:1 Goal: Count substrings that contain all chars of word2 ALGORITHM STEPS 1 Sliding Window Use two pointers (left, right) 2 Track Frequency Count chars in window 3 Check Valid Window has all word2 chars? 4 Count Extensions Add (n - right) to result Window Scan: [b] - need a,c [b,c] - need a [b,c,d] - need a [b,c,d,a] - OK! +1 Shrink left... FINAL RESULT Valid Substring: b c d a "bcda" contains a,b,c Can rearrange to "abc..." Output: 1 OK - Verified Only 1 valid substring found Key Insight: Use sliding window with character frequency tracking. When window contains all required characters, all extensions to the right are also valid. Count them as (n - right). Shrink from left and repeat. This achieves O(n) time with O(26) = O(1) space. TutorialsPoint - Count Substrings That Can Be Rearranged to Contain a String II | Optimal Solution
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