1358. Number of Substrings Containing All Three Characters
Problem Statement
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^4
s
only consists of a, b or c characters.
Intuition
Approach:
As an when we get all occurences of a, b and c
We take all the sub-arrays from that point till end
eg-
abc|abc
At index 2 we get all
So we take n-j
6-2=4 We get 4 sub arrays : abc, abca, abcab, abcabc
Like that
Links
https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/description/
Video Links
Approach 1:
Sliding Window
class Solution {
public:
int numberOfSubstrings(string s) {
unordered_map<char,int> mp;
int ans=0, low=0, n=s.size();
for(int high=0; high<s.size(); high++){
mp[s[high]]++;
while(mp['a'] and mp['b'] and mp['c']){
ans += n-high;
mp[s[low]]--;
low++;
}
}
return ans;
}
};
Approach 2:
Approach 3:
Approach 4:
Similar Problems
Last updated