Given a string str consisting only of the characters ‘a’, ‘b’ and ‘c’, find the number of sub-strings that do not contain all the three characters at the same time.
Input: str = “abc”
The possible substrings are “a”, “b”, “c”, “ab” and “bc”
Input: str = “babac”
Approach: The idea is to use three variables a_index, b_index and c_index to store the latest occurrence of the characters a, b and c and another variable ans to store the number of substrings that dont have at least one of a, b or c and initialize its value to the total number of substrings with length n i.e, n*(n+1)/2, where n is the length of the string.
Now simply traverse the string from the beginning. At each point update the value of variables to the latest value whenever encountered.Since we are indexing with 0, so we are updating the index as i+1 at each step.
Also at each step, you need to find the index of minimum occurrence of the remaining of the two characters not encountered in the current step.
Then simply deduct this index from the variable ans. This is because once you found the index of the minimum of the remaining characters you are sure that any more substrings formed by moving downwards in index will also contain all the three characters.
Hence the total numbers of all such substrings(ones containing all a, b, and c) formed at this step is the found index.
Below is the implementation of the above approach:
- Count substrings with same first and last characters
- Count distinct substrings that contain some characters at most k times
- Recursive solution to count substrings with same first and last characters
- Count number of substrings with exactly k distinct characters
- Count number of substrings of a string consisting of same characters
- Queries for frequencies of characters in substrings
- Find number of substrings of length k whose sum of ASCII value of characters is divisible by k
- Count all substrings having character K
- Count substrings that contain all vowels | SET 2
- Count of total anagram substrings
- Number of substrings with count of each character as k
- Count of substrings of a binary string containing K ones
- Count Substrings with equal number of 0s, 1s and 2s
- Count of substrings which contains a given character K times
- Count substrings with each character occurring at most k times
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.