Given a string str and a character K, the task is to find the count of all the substrings of str that contain the character K.
Input: str = “geeks”, K = ‘g’
“g”, “ge”, “gee”, “geek” and “geeks” are the valid substrings.
Input: str = “geeksforgeeks”, K = ‘k’
Naive approach A simple approach will be to find all the substrings having character K of the given string and return the count;
Efficient approach: For every index i in the string, find the first index j such that i ≤ j and str[j] = K. Now, the substrings str[i…j], str[i…j + 1], str[i…j + 2], …, str[i…n – 1] will all contain the character K at least once. The approach seems to be O(n2) at first but the index j will not be calculated again for every index i, j will be a valid index for all the values of i less than j.
Below is the implementation of the above approach:
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Count substrings that starts with character X and ends with character Y
- Number of substrings with count of each character as k
- Count of substrings which contains a given character K times
- Count substrings with each character occurring at most k times
- Maximize partitions such that no two substrings have any common character
- Print Kth character in sorted concatenated substrings of a string
- Find the count of M character words which have at least one character repeated
- Count substrings with same first and last characters
- Count substrings that contain all vowels | SET 2
- Count Substrings with equal number of 0s, 1s and 2s
- Count of total anagram substrings
- Count of substrings of a binary string containing K ones
- Count of substrings consisting only of vowels
- Count of substrings formed using a given set of characters only
- Count of all unique substrings with non-repeating characters
- Count distinct substrings that contain some characters at most k times
- Count of Palindromic substrings in an Index range
- Count number of substrings with numeric value greater than X
- Count number of substrings with exactly k distinct characters
- Count number of distinct substrings of a given length
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.