Given a string str, a character c and an integer k > 0. The task is to find the number of sub-strings that contain the character c exactly k times.
Input: str = “abada”, c = ‘a’, K = 2
All possible sub-strings are “aba”, “abad”, “bada” and “ada”.
Input: str = “55555”, c = ‘5’, k = 4
Naive approach: A simple solution is to generate all the sub-strings and check whether the count of given character is exactly k times.
Time complexity of this approach is O(n2).
Efficient approach: An efficient solution is to use sliding window technique. Find the sub-string that exactly contains the given character k times starting with character c. Count the number of characters on either side side of the sub-string. Multiply the counts to get the number of possible sub-strings. Time complexity of this approach is O(n).
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count distinct substrings that contain some characters at most k times
- Count of substrings which contains a given character K times
- Count substrings with each character occurring at most k times
- Count substrings that starts with character X and ends with character Y
- Find substrings that contain all vowels
- Count substrings that contain all vowels | SET 2
- Replace every character of string by character whose ASCII value is K times more than it
- Repeat substrings of the given String required number of times
- Count number of substrings with exactly k distinct characters
- Count of sub-strings that contain character X at least once
- Check if a String contains Anagrams of length K which does not contain the character X
- Find Nth smallest number that is divisible by 100 exactly K times
- Count of substrings of length K with exactly K distinct characters
- Queries to print the character that occurs the maximum number of times in a given range
- Count of substrings containing only the given character
- Count words that appear exactly two times in an array of words
- String which when repeated exactly K times gives a permutation of S
- Remove characters from a String that appears exactly K times
- Smallest String consisting of a String S exactly K times as a Substring
- Number of substrings with count of each character as k
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.