Description
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^4sonly consists of a, b or c characters.
Solutions
Sliding window using character counting.
Language: javascript(2026-06-30 07:05)DONE
CPU Performance78.28%
Memory Performance62.12%
/**
* @param {string} s
* @return {number}
*/
var numberOfSubstrings = function(s) {
const n = s.length;
const dp = new Array(26).fill(0);
let res = 0;
let left = 0;
for (let right = 0; right < n; right++) {
dp[s.charCodeAt(right) - 97]++;
while (dp[0] > 0 && dp[1] > 0 && dp[2] > 0) {
res += n - right;
dp[s.charCodeAt(left) - 97]--;
left++;
}
}
return res;
};