VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-substrings-containing-only-the-given-character/

⇱ Count of substrings containing only the given character - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of substrings containing only the given character

Last Updated : 15 Jul, 2025

Given a string S and a character C, the task is to count the number of substrings of S that contains only the character C.
Examples: 
 

Input: S = "0110111", C = '1' 
Output:
Explanation: 
The substrings containing only '1' are:
 "1" — 5 times 
"11" — 3 times 
"111" — 1 time 
Hence, the count is 9.


Input: S = "geeksforgeeks", C = 'e' 
Output:
 


 


Naive Approach: 
The simplest approach is to generate all possible substrings of the given string S and count the substrings which contains only character C. 
Time Complexity: O(N3
Space Complexity: O(1)
Efficient Approach: 
To optimize the above approach, the fact that a string of length N forms N*(N+1)/2 substrings can be applied. Therefore, for N consecutive occurrence of character C in the string, N*(N+1)/2 substrings are generated. Hence, iterate through the entire length of the string S and for each consecutive substring of character C, count the possible number of substrings possible from them and add to the total count of substrings possible.
 

Illustration: 
S = "0110111", C = '1' 
 

👁 Image


Below is the implementation of the above approach:
 


Output: 
6

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 

Comment