#1358
Number of Substrings Containing All Three Characters
MediumHash TableStringSliding WindowSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a sliding window approach to efficiently count valid substrings. By maintaining a window that contains at least one 'a', 'b', and 'c', we can quickly calculate how many substrings can be formed from this window.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a frequency map to count occurrences of 'a', 'b', and 'c'.
- 2Step 2: Use two pointers (left and right) to represent the current window.
- 3Step 3: Expand the right pointer to include characters until the window contains at least one of each character.
- 4Step 4: Once valid, count all substrings that can be formed from the left pointer to the right pointer, then move the left pointer to find new valid windows.
solution.py16 lines
1# Full working Python code
2
3def count_substrings(s):
4 count = 0
5 left = 0
6 freq = {'a': 0, 'b': 0, 'c': 0}
7 for right in range(len(s)):
8 freq[s[right]] += 1
9 while freq['a'] > 0 and freq['b'] > 0 and freq['c'] > 0:
10 count += len(s) - right
11 freq[s[left]] -= 1
12 left += 1
13 return count
14
15# Example usage
16print(count_substrings('abcabc'))ℹ
Complexity note: The time complexity is O(n) because we traverse the string with two pointers, and each character is processed a limited number of times. The space complexity is O(1) since we only use a fixed-size array for character counts.
- 1Using a sliding window allows for efficient substring counting without redundant checks.
- 2The frequency array helps track the presence of required characters in constant time.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.