Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
Given a string s consisting only of characters a, b and c.
Return the number of substrings containing at least one occurrence of all these characters a, b and c.
Example 1:
Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again).
Example 2:
Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb".
Example 3:
Input: s = "abc" Output: 1
Constraints:
3 <= s.length <= 5 x 10^4s only consists of a, b or c characters.Problem summary: Given a string s consisting only of characters a, b and c. Return the number of substrings containing at least one occurrence of all these characters a, b and c.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Sliding Window
"abcabc"
"aaacb"
"abc"
vowels-of-all-substrings)count-complete-substrings)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1358: Number of Substrings Containing All Three Characters
class Solution {
public int numberOfSubstrings(String s) {
int[] d = new int[] {-1, -1, -1};
int ans = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
d[c - 'a'] = i;
ans += Math.min(d[0], Math.min(d[1], d[2])) + 1;
}
return ans;
}
}
// Accepted solution for LeetCode #1358: Number of Substrings Containing All Three Characters
func numberOfSubstrings(s string) (ans int) {
d := [3]int{-1, -1, -1}
for i, c := range s {
d[c-'a'] = i
ans += min(d[0], min(d[1], d[2])) + 1
}
return
}
# Accepted solution for LeetCode #1358: Number of Substrings Containing All Three Characters
class Solution:
def numberOfSubstrings(self, s: str) -> int:
d = {"a": -1, "b": -1, "c": -1}
ans = 0
for i, c in enumerate(s):
d[c] = i
ans += min(d["a"], d["b"], d["c"]) + 1
return ans
// Accepted solution for LeetCode #1358: Number of Substrings Containing All Three Characters
struct Solution;
impl Solution {
fn number_of_substrings(s: String) -> i32 {
let mut count: [usize; 3] = [0; 3];
let s: Vec<u8> = s.bytes().collect();
let n = s.len();
let mut j = 0;
let mut res = 0;
for i in 0..n {
count[(s[i] - b'a') as usize] += 1;
while count[0] > 0 && count[1] > 0 && count[2] > 0 {
count[(s[j] - b'a') as usize] -= 1;
j += 1;
}
res += j;
}
res as i32
}
}
#[test]
fn test() {
let s = "abcabc".to_string();
let res = 10;
assert_eq!(Solution::number_of_substrings(s), res);
let s = "aaacb".to_string();
let res = 3;
assert_eq!(Solution::number_of_substrings(s), res);
let s = "abc".to_string();
let res = 1;
assert_eq!(Solution::number_of_substrings(s), res);
}
// Accepted solution for LeetCode #1358: Number of Substrings Containing All Three Characters
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1358: Number of Substrings Containing All Three Characters
// class Solution {
// public int numberOfSubstrings(String s) {
// int[] d = new int[] {-1, -1, -1};
// int ans = 0;
// for (int i = 0; i < s.length(); ++i) {
// char c = s.charAt(i);
// d[c - 'a'] = i;
// ans += Math.min(d[0], Math.min(d[1], d[2])) + 1;
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
For each starting index, scan the next k elements to compute the window aggregate. There are n−k+1 starting positions, each requiring O(k) work, giving O(n × k) total. No extra space since we recompute from scratch each time.
The window expands and contracts as we scan left to right. Each element enters the window at most once and leaves at most once, giving 2n total operations = O(n). Space depends on what we track inside the window (a hash map of at most k distinct elements, or O(1) for a fixed-size window).
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.