Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: word1 = "bcca", word2 = "abc"
Output: 1
Explanation:
The only valid substring is "bcca" which can be rearranged to "abcc" having "abc" as a prefix.
Example 2:
Input: word1 = "abcabc", word2 = "abc"
Output: 10
Explanation:
All the substrings except substrings of size 1 and size 2 are valid.
Example 3:
Input: word1 = "abcabc", word2 = "aaabc"
Output: 0
Constraints:
1 <= word1.length <= 1061 <= word2.length <= 104word1 and word2 consist only of lowercase English letters.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Sliding Window
"bcca" "abc"
"abcabc" "abc"
"abcabc" "aaabc"
minimum-window-substring)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3298: Count Substrings That Can Be Rearranged to Contain a String II
class Solution {
public long validSubstringCount(String word1, String word2) {
if (word1.length() < word2.length()) {
return 0;
}
int[] cnt = new int[26];
int need = 0;
for (int i = 0; i < word2.length(); ++i) {
if (++cnt[word2.charAt(i) - 'a'] == 1) {
++need;
}
}
long ans = 0;
int[] win = new int[26];
for (int l = 0, r = 0; r < word1.length(); ++r) {
int c = word1.charAt(r) - 'a';
if (++win[c] == cnt[c]) {
--need;
}
while (need == 0) {
c = word1.charAt(l) - 'a';
if (win[c] == cnt[c]) {
++need;
}
--win[c];
++l;
}
ans += l;
}
return ans;
}
}
// Accepted solution for LeetCode #3298: Count Substrings That Can Be Rearranged to Contain a String II
func validSubstringCount(word1 string, word2 string) (ans int64) {
if len(word1) < len(word2) {
return 0
}
cnt := [26]int{}
need := 0
for _, c := range word2 {
cnt[c-'a']++
if cnt[c-'a'] == 1 {
need++
}
}
win := [26]int{}
l := 0
for _, c := range word1 {
i := int(c - 'a')
win[i]++
if win[i] == cnt[i] {
need--
}
for need == 0 {
i = int(word1[l] - 'a')
if win[i] == cnt[i] {
need++
}
win[i]--
l++
}
ans += int64(l)
}
return
}
# Accepted solution for LeetCode #3298: Count Substrings That Can Be Rearranged to Contain a String II
class Solution:
def validSubstringCount(self, word1: str, word2: str) -> int:
if len(word1) < len(word2):
return 0
cnt = Counter(word2)
need = len(cnt)
ans = l = 0
win = Counter()
for c in word1:
win[c] += 1
if win[c] == cnt[c]:
need -= 1
while need == 0:
if win[word1[l]] == cnt[word1[l]]:
need += 1
win[word1[l]] -= 1
l += 1
ans += l
return ans
// Accepted solution for LeetCode #3298: Count Substrings That Can Be Rearranged to Contain a String II
/**
* [3298] Count Substrings That Can Be Rearranged to Contain a String II
*/
pub struct Solution {}
// submission codes start here
use std::collections::HashMap;
impl Solution {
pub fn valid_substring_count(word1: String, word2: String) -> i64 {
let word1: Vec<char> = word1.chars().collect();
let mut word_map = HashMap::with_capacity(26);
for c in word2.chars() {
let entry = word_map.entry(c).or_insert(0);
*entry -= 1;
}
let mut result = 0;
let mut count = word_map.iter().filter(|c| c.1 < &0).count();
let mut right = 0;
for left in 0..word1.len() {
while right < word1.len() && count > 0 {
let entry = word_map.entry(word1[right]).or_insert(0);
*entry += 1;
if *entry == 0 {
count -= 1;
}
right += 1;
}
if count == 0 {
result += (word1.len() - right + 1) as i64;
}
let entry = word_map.entry(word1[left]).or_insert(0);
*entry -= 1;
if *entry == -1 {
count += 1;
}
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_3298() {
assert_eq!(
1,
Solution::valid_substring_count("bcca".to_owned(), "abc".to_owned())
);
assert_eq!(
10,
Solution::valid_substring_count("abcabc".to_owned(), "abc".to_owned())
);
assert_eq!(
0,
Solution::valid_substring_count("abcabc".to_owned(), "aaabc".to_owned())
);
}
}
// Accepted solution for LeetCode #3298: Count Substrings That Can Be Rearranged to Contain a String II
function validSubstringCount(word1: string, word2: string): number {
if (word1.length < word2.length) {
return 0;
}
const cnt: number[] = Array(26).fill(0);
let need: number = 0;
for (const c of word2) {
if (++cnt[c.charCodeAt(0) - 97] === 1) {
++need;
}
}
const win: number[] = Array(26).fill(0);
let [ans, l] = [0, 0];
for (const c of word1) {
const i = c.charCodeAt(0) - 97;
if (++win[i] === cnt[i]) {
--need;
}
while (need === 0) {
const j = word1[l].charCodeAt(0) - 97;
if (win[j] === cnt[j]) {
++need;
}
--win[j];
++l;
}
ans += l;
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.