#3298

Count Substrings That Can Be Rearranged to Contain a String II

Hard
Hash TableStringSliding WindowHash MapSliding Window
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a sliding window technique to maintain a count of characters in the current window of `word1` and checks if it can satisfy the character requirements of `word2`. This reduces the need to generate all substrings explicitly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Create a frequency map of characters in `word2`.
  2. 2Step 2: Initialize a sliding window on `word1` with two pointers.
  3. 3Step 3: Expand the window by moving the right pointer and update the frequency count.
  4. 4Step 4: When the window size exceeds the length of `word2`, move the left pointer to shrink the window.
  5. 5Step 5: Count valid substrings when the current window can rearrange to contain `word2`.
solution.py19 lines
1# Full working Python code
2from collections import Counter
3
4def count_valid_substrings(word1, word2):
5    word2_count = Counter(word2)
6    window_count = Counter()
7    valid_count = 0
8    left = 0
9    for right in range(len(word1)):
10        window_count[word1[right]] += 1
11        while right - left + 1 > len(word2):
12            window_count[word1[left]] -= 1
13            if window_count[word1[left]] == 0:
14                del window_count[word1[left]]
15            left += 1
16        if all(window_count[c] >= word2_count[c] for c in word2_count):
17            valid_count += right - left + 1
18    return valid_count
19

Complexity note: This complexity is achieved because we only traverse `word1` once with the sliding window, maintaining counts in constant time.

  • 1Understanding character frequency is crucial for rearrangement problems.
  • 2Sliding window technique is effective for substring problems with constraints.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.