#2953
Count Complete Substrings
HardHash TableStringSliding WindowSliding WindowHash Map
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 technique to efficiently count substrings that meet the criteria. By maintaining a frequency map and adjusting the window size dynamically, we can avoid the overhead of generating all substrings.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a frequency map to count characters in the current window.
- 2Step 2: Use two pointers to define the window's start and end positions.
- 3Step 3: Expand the window by moving the end pointer and updating the frequency map.
- 4Step 4: Check if the current window meets the conditions for being complete. If so, count it.
- 5Step 5: If the window exceeds the valid conditions, move the start pointer to shrink the window.
solution.py15 lines
1def count_complete_substrings(word, k):
2 count = 0
3 n = len(word)
4 freq = {}
5 start = 0
6 for end in range(n):
7 freq[word[end]] = freq.get(word[end], 0) + 1
8 while any(v > k for v in freq.values()):
9 freq[word[start]] -= 1
10 if freq[word[start]] == 0:
11 del freq[word[start]]
12 start += 1
13 if all(v == k for v in freq.values()) and all(abs(ord(word[i]) - ord(word[i + 1])) <= 2 for i in range(start, end)):
14 count += 1
15 return countℹ
Complexity note: The time complexity is O(n) because we only traverse the string once with the sliding window technique, adjusting the window size dynamically. The space complexity is O(n) due to the frequency map storing character counts.
- 1Using a sliding window can significantly reduce the time complexity from O(n²) to O(n).
- 2Maintaining a frequency map allows for quick checks on character counts.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.