VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-all-substrings-having-character-k/

⇱ Count all substrings having character K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count all substrings having character K

Last Updated : 25 Aug, 2021

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.
Examples: 

Input: str = "geeks", K = 'g' 
Output:
"g", "ge", "gee", "geek" and "geeks" are the valid substrings.
Input: str = "geeksforgeeks", K = 'k' 
Output: 56 
 


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:  


Output: 
56

 
Comment
Article Tags:
Article Tags: