Python 1358.py
class Solution:
def numberOfSubstrings(self, s: str) -> int:
result = 0
freq = { "a": 0, "b": 0, "c": 0 }
right = 0
for left in range(len(s)):
# find minimal string starting at "left"
while right < len(s) and freq["a"] * freq["b"] * freq["c"] == 0: # zero if at least one counter is zero
freq[s[right]] += 1
right += 1
# no more valid strings
if freq["a"] * freq["b"] * freq["c"] == 0:
break
# all strings from "right" to the end are valid
result += len(s) - right + 1
freq[s[left]] -= 1
return result
Difficulty
and has an acceptance rate of about 74% (800k+ submissions).
Typical patterns to solve this problem:
- Hash Table
- Sliding Window
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of counting substrings that contain at least one occurrence of each character 'a', 'b', and 'c'. It employs a sliding-window technique with two pointers, left and right, that move through the input string exactly once. Frequency counters for the three required characters are maintained in a dictionary, allowing the algorithm to determine when a window satisfies the “all three characters present” condition. When such a window is found, the number of valid substrings that start at the current left index is added to the result in constant time.
Key Steps
Initialization
The function begins by setting up the result accumulator, a frequency map for the three characters, and the right-hand pointer. The frequency map starts with zero counts for 'a', 'b', and 'c'.
result = 0
freq = { "a": 0, "b": 0, "c": 0 }
right = 0
Expanding the Right Pointer
For each possible starting position left, the algorithm expands the right pointer until the current window contains at least one of each required character. The condition freq["a"] * freq["b"] * freq["c"] == 0 evaluates to true as long as any count is zero, so the loop continues while the window is incomplete.
while right < len(s) and freq["a"] * freq["b"] * freq["c"] == 0:
freq[s[right]] += 1
right += 1
Early Termination
If the right pointer reaches the end of the string without satisfying the condition, the outer loop terminates because no further substrings can meet the requirement. This handles the edge case where the remaining suffix of the string lacks at least one of the three characters.
if freq["a"] * freq["b"] * freq["c"] == 0:
break
Counting Valid Substrings
When the window first becomes valid, every extension of the window to the right (including the current right position) also remains valid because adding characters cannot remove the presence of 'a', 'b', or 'c'. Therefore, the number of substrings that start at left and satisfy the condition equals the number of possible right endpoints, which is len(s) - right + 1. This value is added directly to the result.
result += len(s) - right + 1
Shrinking from the Left
Before moving to the next left index, the algorithm decrements the count of the character that is being left behind. This prepares the frequency map for the next iteration without recomputing the entire window.
freq[s[left]] -= 1
Final Return
After iterating through all possible starting positions, the accumulated result is returned.
return result
Edge Cases Handled
The code gracefully manages several boundary conditions:
- Empty Input - When
sis an empty string, the outer loop never executes, and the function returns0, correctly indicating that no substrings exist. - Missing Characters - If the input lacks any one of
'a','b', or'c', the inner while loop will eventually exhaust the string without satisfying the product condition. The subsequent break exits the outer loop, yielding a result of0. - Single-Character Strings - For strings of length one, the same logic applies: the product condition fails, the loop breaks, and the result remains
0. - Repeated Characters - When a character appears many times consecutively, the sliding window still expands only until the first occurrence of each required character, avoiding unnecessary work.
Performance Optimizations
The implementation incorporates several subtle optimizations that keep the execution efficient:
- Single Pass with Two Pointers - By never resetting the
rightpointer for each newleft, the algorithm ensures that each character of the string is visited at most twice, once when entering the window and once when leaving it. - Compact Condition Check - Using the product
freq["a"] * freq["b"] * freq["c"]to test for the presence of all three characters reduces the number of logical operations compared to checking each count individually. - Constant-Time Contribution Calculation - Once a valid window is identified, the number of qualifying substrings is computed with a simple arithmetic expression, avoiding any inner loops or additional scans.
- In-Place Frequency Updates - The frequency dictionary is updated incrementally as the window slides, eliminating the need for auxiliary data structures or recomputation of counts for each new window.
ELI5 - Simplified Explanation
Imagine a long train track made of letter blocks like a, b, and c connected in a row. The goal is to count every possible tunnel you can build that captures at least one of each letter.
First, think of two friends holding markers on the track. One friend stands at the start and the other friend walks forward to find a group of blocks that contains at least one a, one b, and one c. Once they find a group that has all three, they stop and look at how many blocks are left over at the end of the track. Because that group is already complete with the three letters, any larger group that includes those extra blocks at the end will also be a winner.
The first friend then steps forward to shrink the group from the other side, and the second friend starts moving forward again to see if they can find another set. This keeps happening until the whole track has been checked, carefully toting up every single valid group found along the way. It is like putting together a puzzle by sliding a window across the line to see how many different ways those letters can be grouped together.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||||
| WalkCCC | C++ | Java | Python | |||||||
| leetcode.ca | C++ | Java | Go | Python | Rust | TS | ||||
| Progiez | C++ | Java | Python | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lzl124631x | C++ | |||||||||
| Shamik07 | Dart | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| fartem | Ruby | |||||||||
| fsq | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lzl124631x | C++ | |||||||||
| Shamik07 | Dart | |||||||||
| varunu28 | Java | |||||||||
| wisdompeak | C++ | |||||||||
| withaarzoo | C++ |
Videos
Similar Problems
- problem 2063: Vowels of All Substrings
Solved On The Same Day
- problem 1248: Count Number of Nice Subarrays
- problem 1371: Find the Longest Substring Containing Vowels in Even Counts
- problem 1410: HTML Entity Parser
- problem 1481: Least Number of Unique Integers after K Removals
- problem 1600: Throne Inheritance
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality