Number of Substrings Containing All Three Characters
LeetCode 1358 · Medium · solution, intuition & step-by-step walkthrough
Ending at i, valid starts = 1 + min(last a, last b, last c).
This is how I solved Number of Substrings Containing All Three Characters (LeetCode 1358), a medium problem from the Counting Subarrays (Exactly K = AtMost K − AtMost K−1) pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Track the latest index where each of a, b and c appeared. For a substring ending at i to contain all three, it must start at or before the smallest of those indices — so there are min(last) + 1 valid starts.
Approach
- 1
last index of a, b, c start at −1.
- 2
Update the index of s[i].
- 3
If all three have appeared, add 1 + min(last indices).
- 4
Earlier versions: O(n²) set scans.
How I solved it
Last-seen indicesPythonO(n) time · O(1) space
class Solution:
def numberOfSubstrings(self, s):
mpp = {'a': -1, 'b': -1, 'c': -1}
count = 0
for i in range(len(s)):
mpp[s[i]] = i
if mpp['a'] != -1 and mpp['b'] != -1 and mpp['c'] != -1:
count = count + (1 + min(mpp['a'], mpp['b'], mpp['c']))
return countNumber of Substrings Containing All Three Characters — FAQ
What is the intuition behind Number of Substrings Containing All Three Characters?
Track the latest index where each of a, b and c appeared. For a substring ending at i to contain all three, it must start at or before the smallest of those indices — so there are min(last) + 1 valid starts.
How do you solve Number of Substrings Containing All Three Characters (LeetCode 1358)?
1. last index of a, b, c start at −1. 2. Update the index of s[i]. 3. If all three have appeared, add 1 + min(last indices). 4. Earlier versions: O(n²) set scans.
What is the time and space complexity of Number of Substrings Containing All Three Characters?
Time: O(n). Space: O(1). (Accepted approach: Last-seen indices.)
What are common mistakes in Number of Substrings Containing All Three Characters?
Count by end position to avoid double-counting.