Number of Substrings Containing All Three Characters
Number of Substrings Containing All Three Characters is a medium arrays & hashing problem solved with the sliding window · hash map pattern.
The best approach, optimal (sliding window with counts), runs in O(n) time and O(1) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force up.
Problem
Given a string s made of only a, b and c, count the substrings that contain at least one of each of the three letters.
Examples
Example 1
- Input
s = "abcab"- Output
6- Why
- Starting at 0: abc, abca, abcab. At 1: bca, bcab. At 2: cab.
Example 2
- Input
s = "aaacb"- Output
3- Why
- aaacb, aacb and acb.
Constraints
3 <= s.length <= 5 * 10^4- s contains only a, b and c.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 11 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force | O(n²) | O(1) |
| Optimal (sliding window with counts) | O(n) | O(1) |
1Brute force
O(n²)O(1)For each start, extend until all three letters are present; every longer substring from that start also qualifies.
- For each i, scan j until counts of a, b, c are all positive.
- Add n - j to the answer.
class Solution {
public int numberOfSubstrings(String s) {
int n = s.length(), total = 0;
for (int i = 0; i < n; i++) {
int[] c = new int[3];
for (int j = i; j < n; j++) {
c[s.charAt(j) - 'a']++;
if (c[0] > 0 && c[1] > 0 && c[2] > 0) { total += n - j; break; }
}
}
return total;
}
}class Solution:
def numberOfSubstrings(self, s: str) -> int:
n, total = len(s), 0
for i in range(n):
c = [0] * 3
for j in range(i, n):
c[ord(s[j]) - ord('a')] += 1
if c[0] > 0 and c[1] > 0 and c[2] > 0:
total += n - j
break
return totalclass Solution {
public:
int numberOfSubstrings(string s) {
int n = s.size(), total = 0;
for (int i = 0; i < n; i++) {
int c[3] = {0, 0, 0};
for (int j = i; j < n; j++) {
c[s[j] - 'a']++;
if (c[0] > 0 && c[1] > 0 && c[2] > 0) { total += n - j; break; }
}
}
return total;
}
};function numberOfSubstrings(s) {
const n = s.length;
let total = 0;
for (let i = 0; i < n; i++) {
const c = [0, 0, 0];
for (let j = i; j < n; j++) {
c[s.charCodeAt(j) - 97]++;
if (c[0] > 0 && c[1] > 0 && c[2] > 0) { total += n - j; break; }
}
}
return total;
}2Optimal (sliding window with counts)
O(n)O(1)Move r right, adding s[r]. While the window [l, r] has all three letters, every substring starting at l and ending at r or later is valid, so add n - r, then drop s[l] and move l.
- Keep counts of a, b, c in the window.
- For each r, add s[r].
- While all counts > 0: total += n - r; remove s[l]; l++.
class Solution {
public int numberOfSubstrings(String s) {
int n = s.length(), l = 0, total = 0;
int[] c = new int[3];
for (int r = 0; r < n; r++) {
c[s.charAt(r) - 'a']++;
while (c[0] > 0 && c[1] > 0 && c[2] > 0) {
total += n - r;
c[s.charAt(l++) - 'a']--;
}
}
return total;
}
}class Solution:
def numberOfSubstrings(self, s: str) -> int:
n, l, total = len(s), 0, 0
c = [0] * 3
for r in range(n):
c[ord(s[r]) - ord('a')] += 1
while c[0] > 0 and c[1] > 0 and c[2] > 0:
total += n - r
c[ord(s[l]) - ord('a')] -= 1
l += 1
return totalclass Solution {
public:
int numberOfSubstrings(string s) {
int n = s.size(), l = 0, total = 0;
int c[3] = {0, 0, 0};
for (int r = 0; r < n; r++) {
c[s[r] - 'a']++;
while (c[0] > 0 && c[1] > 0 && c[2] > 0) {
total += n - r;
c[s[l++] - 'a']--;
}
}
return total;
}
};function numberOfSubstrings(s) {
const n = s.length;
let l = 0, total = 0;
const c = [0, 0, 0];
for (let r = 0; r < n; r++) {
c[s.charCodeAt(r) - 97]++;
while (c[0] > 0 && c[1] > 0 && c[2] > 0) {
total += n - r;
c[s.charCodeAt(l++) - 97]--;
}
}
return total;
}Edge cases to test
- One letter never appears (answer 0)
- The minimal window is at the very end
Hints
Hint 1
If s[l..r] contains all three letters, then so does every extension s[l..r'] for r' >= r.
FAQ
What is the best time complexity for Number of Substrings Containing All Three Characters?
Optimal (sliding window with counts) runs in O(n) time and O(1) extra space.
Which pattern does Number of Substrings Containing All Three Characters use?
It is a arrays & hashing problem that uses the sliding window · hash map pattern. Other problems with the same pattern: Minimum Window Substring, Longest Substring with At Most K Distinct Characters, Contains Duplicate III.
Is there a brute force solution for Number of Substrings Containing All Three Characters?
Yes. Brute force takes O(n²) time and O(1) space. For each start, extend until all three letters are present; every longer substring from that start also qualifies.
Which edge cases should I test for Number of Substrings Containing All Three Characters?
One letter never appears (answer 0); The minimal window is at the very end.