#3297
Count Substrings That Can Be Rearranged to Contain a String I
MediumHash TableStringSliding WindowHash MapSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a sliding window approach combined with character frequency counting. This allows us to efficiently check if any substring can be rearranged to contain `word2` as a prefix without generating all substrings explicitly.
⚙️
Algorithm
3 steps- 1Step 1: Count the frequency of characters in `word2`.
- 2Step 2: Use a sliding window of size equal to `word2` to traverse `word1`.
- 3Step 3: For each window, maintain a frequency count of characters and check if it can cover the frequency of `word2`.
solution.py16 lines
1def countValidSubstrings(word1, word2):
2 from collections import Counter
3 count2 = Counter(word2)
4 valid_count = 0
5 n, m = len(word1), len(word2)
6 count1 = Counter()
7 for i in range(n):
8 count1[word1[i]] += 1
9 if i >= m:
10 count1[word1[i - m]] -= 1
11 if count1[word1[i - m]] == 0:
12 del count1[word1[i - m]]
13 if i >= m - 1:
14 if all(count1[char] >= count2[char] for char in count2):
15 valid_count += 1
16 return valid_countℹ
Complexity note: The time complexity is O(n) because we traverse `word1` once with a sliding window. The space complexity is O(n) due to the storage of character counts.
- 1Character frequency is key to determining valid substrings.
- 2Sliding window helps efficiently manage substring checks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.