Count Substrings That Can Be Rearranged to Contain a String I - 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.

Input & Output

Example 1 — Basic Case
$ Input: word1 = "bcca", word2 = "abc"
Output: 1
💡 Note: Only one valid substring "bcc" at index 0-2. It can be rearranged as "bcc" → "abc" + "c" (abc as prefix)
Example 2 — Multiple Valid Substrings
$ Input: word1 = "abcabc", word2 = "abc"
Output: 10
💡 Note: Valid substrings: "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), "abc"(3-5)
Example 3 — No Valid Substrings
$ Input: word1 = "abcab", word2 = "abc"
Output: 6
💡 Note: Valid substrings: "abc"(0-2), "abca"(0-3), "abcab"(0-4), "bca"(1-3), "bcab"(1-4), "cab"(2-4). Total = 6 valid substrings.

Constraints

  • 1 ≤ word2.length ≤ word1.length ≤ 104
  • word1 and word2 consist only of lowercase English letters

Visualization

Tap to expand
Count Valid Substrings INPUT word1 = "bcca" b idx 0 c idx 1 c idx 2 a idx 3 word2 = "abc" a b c Need: a(1), b(1), c(1) All Substrings: "b","c","c","a" "bc","cc","ca" "bcc","cca" "bcca" (10 total substrings) ALGORITHM STEPS 1 Sliding Window Two pointers: left, right 2 Count Chars Track freq in window 3 Check Valid Has all chars of word2? 4 Shrink + Count Add valid substrings Window Check: "bcca" b c c a a:1 b:1 c:2 Contains a,b,c -- OK Can rearrange to "abc..." FINAL RESULT Valid Substrings Found: "bcca" Can rearrange to "abcc" which has "abc" prefix Invalid Examples: "bc" - missing 'a' "cca" - missing 'b' "bcc" - missing 'a' Output: 1 Key Insight: A substring is valid if it contains at least all characters of word2 (with sufficient frequency). Use sliding window with character frequency map to efficiently check each window. Time Complexity: O(n) where n = length of word1. Only "bcca" can be rearranged to start with "abc". TutorialsPoint - Count Substrings That Can Be Rearranged to Contain a String I | Optimal Solution
Asked in
Google 25 Microsoft 18
28.0K Views
Medium Frequency
~25 min Avg. Time
890 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