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 don’t 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:
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Count substrings with same first and last characters
- Count of Substrings that can be formed without using the given list of Characters
- Count number of substrings with exactly k distinct characters
- Count of all unique substrings with non-repeating 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 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 of ungrouped characters after dividing a string into K groups of distinct characters
- Count all substrings having character K
- Count substrings that contain all vowels | SET 2
- Count Substrings with equal number of 0s, 1s and 2s
- Number of substrings with count of each character as k
- Count of substrings which contains a given character 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 email@example.com. 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.