Number of Substrings Containing All Three Characters (LeetCode 1358): Solution and Explanation
Given a string of the letters a, b and c, count the substrings that contain each of the three letters at least once.
Intuition
Count substrings by their end index i. If a substring ending at i contains all three letters, then making it longer on the left keeps all three letters. So the good starts for end i are exactly 0..p for some cutoff p.
The cutoff is the latest start that still reaches every letter. A substring s[p..i] has an a only if p is at or before the most recent a, and the same for b and c.
So p = min(last_a, last_b, last_c), and end i adds p + 1 substrings. While a letter has not appeared, its last index is -1, which makes the contribution 0 with no special case.
This is a sliding window in disguise: p + 1 is the left edge the shrinking-window solution would reach, but here three numbers replace the whole window.
Approach: Last-seen positions
- Set
last = [-1, -1, -1]for a, b and c, andcount = 0. - For each index
i, setlast[s[i] - 'a'] = i. - Add
min(last) + 1tocount. - Return
count.
Step-by-step example
s = "abcabc"
- i = 0 and i = 1: only a and b are seen, so
min(last) = -1and nothing is added. - i = 2 ('c'):
last = [0, 1, 2], min 0, add 1 ("abc"). count = 1. - i = 3 ('a'):
last = [3, 1, 2], min 1, add 2. count = 3. - i = 4 ('b'):
last = [3, 4, 2], min 2, add 3. count = 6. - i = 5 ('c'):
last = [3, 4, 5], min 3, add 4. count = 10, the answer.
Code: Python, Java, C++
1class Solution:
2 def numberOfSubstrings(self, s: str) -> int:
3 last = [-1, -1, -1]
4 count = 0
5 for i, ch in enumerate(s):
6 last[ord(ch) - ord('a')] = i
7 count += min(last) + 1
8 return count1class Solution {
2 public int numberOfSubstrings(String s) {
3 int[] last = {-1, -1, -1};
4 int count = 0;
5 for (int i = 0; i < s.length(); i++) {
6 last[s.charAt(i) - 'a'] = i;
7 count += Math.min(last[0], Math.min(last[1], last[2])) + 1;
8 }
9 return count;
10 }
11}1class Solution {
2public:
3 int numberOfSubstrings(string s) {
4 int last[3] = {-1, -1, -1};
5 int count = 0;
6 for (int i = 0; i < (int)s.size(); i++) {
7 last[s[i] - 'a'] = i;
8 count += min({last[0], last[1], last[2]}) + 1;
9 }
10 return count;
11 }
12};Time and space complexity
O(n)
Each character is handled once with a constant amount of work.
O(1)
Only three positions and a counter are stored.
Other approaches
Shrinking window with letter counts (time O(n), space O(1))
Grow a window to the right and keep counts of a, b and c. While all three counts are positive, every end from right to the end of the string works, so add n - right and shrink from the left.
Complement counting (time O(n), space O(1))
Count all n(n+1)/2 substrings and subtract those missing at least one letter, using inclusion-exclusion over runs that avoid a letter. Correct but harder to get right.
Check every substring (time O(n^2), space O(1))
For each start, extend the end until all three letters appear; then every longer end works too. Without that shortcut it is cubic, with it quadratic.
Common mistakes
- Adding
min(last)instead ofmin(last) + 1. Starts are 0-based, so cutoffpallowsp + 1starts. - Starting
lastat 0 instead of -1, which counts substrings before a letter has appeared. - Counting with the shrinking window and adding
right - left + 1instead of the number of valid starts or ends. - Assuming the answer is small: for 50,000 characters it can exceed a billion, close to the 32-bit limit.
Frequently asked questions
Why is the number of valid starts min(last) + 1?
A start p works when p is at or before the latest a, the latest b and the latest c. The tightest of those is the smallest one, and starts 0 through it make min(last) + 1 options.
How does this extend to more letters?
Keep one last-seen index per required letter and add the minimum plus one. For many letters, a shrinking window with counts is often simpler than taking a minimum over a large array.
Is this really a sliding window problem?
Yes. The minimum of the last positions is where the left edge of the shortest valid window ending at i sits, so the solution tracks a window without moving a pointer explicitly.