Skip to content

Practice Count Substrings That Can Be Rearranged to Contain a String II

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Hard#3298
LeetCode Problem

Count Substrings That Can Be Rearranged to Contain a String II

Problem Statement

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.

Source: Count Substrings That Can Be Rearranged to Contain a String II on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
word1 = "bcca", word2 = "abc"
Output
1

# Example 2

Input
word1 = "abcabc", word2 = "abc"
Output
10

# Example 3

Input
word1 = "abcabc", word2 = "aaabc"
Output
0

Constraints

1 <= word1.length <= 10^6
1 <= word2.length <= 10^4
word1 and word2 consist only of lowercase English letters.

Related LeetCode Problems

Practice more problems similar to Count Substrings That Can Be Rearranged to Contain a String II.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.