Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Count substrings with k distinct characters
Next article icon

Count all substrings having character K

Last Updated : 25 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 5 
“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:  

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return the index of the
// next occurrence of character ch in str
// starting from the given index
int nextOccurrence(string str, int n,
                   int start, char ch)
{
    for (int i = start; i < n; i++) {
 
        // Return the index of the first
        // occurrence of ch
        if (str[i] == ch)
            return i;
    }
 
    // No occurrence found
    return -1;
}
 
// Function to return the count of all
// the substrings of str which contain
// the character ch at least one
int countSubStr(string str, int n, char ch)
{
 
    // To store the count of valid substrings
    int cnt = 0;
 
    // Index of the first occurrence of ch in str
    int j = nextOccurrence(str, n, 0, ch);
    for (int i = 0; i < n; i++) {
        while (j != -1 && j < i) {
            j = nextOccurrence(str, n, j + 1, ch);
        }
 
        // No occurrence of ch after index i in str
        if (j == -1)
            break;
 
        // Substrings starting at index i
        // and ending at indices j, j+1, ..., n-1
        // are all valid substring
        cnt += (n - j);
    }
 
    return cnt;
}
 
// Driver code
int main()
{
 
    string str = "geeksforgeeks";
    int n = str.length();
    char ch = 'k';
 
    cout << countSubStr(str, n, ch);
 
    return 0;
}
 
 

Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
     
    // Function to return the index of the
    // next occurrence of character ch in str
    // starting from the given index
    static int nextOccurrence(String str, int n,
                              int start, char ch)
    {
        for (int i = start; i < n; i++)
        {
     
            // Return the index of the first
            // occurrence of ch
            if (str.charAt(i) == ch)
                return i;
        }
     
        // No occurrence found
        return -1;
    }
     
    // Function to return the count of all
    // the substrings of str which contain
    // the character ch at least one
    static int countSubStr(String str,
                           int n, char ch)
    {
     
        // To store the count of valid substrings
        int cnt = 0;
     
        // Index of the first occurrence of ch in str
        int j = nextOccurrence(str, n, 0, ch);
        for (int i = 0; i < n; i++)
        {
            while (j != -1 && j < i)
            {
                j = nextOccurrence(str, n, j + 1, ch);
            }
     
            // No occurrence of ch after index i in str
            if (j == -1)
                break;
     
            // Substrings starting at index i
            // and ending at indices j, j+1, ..., n-1
            // are all valid substring
            cnt += (n - j);
        }
        return cnt;
    }
     
    // Driver code
    static public void main ( String []arg)
    {
        String str = "geeksforgeeks";
        int n = str.length();
        char ch = 'k';
         
        System.out.println(countSubStr(str, n, ch));
    }
}
 
// This code is contributed by PrinciRaj1992
 
 

Python3




# Python3 implementation of the approach
 
# Function to return the index of the
# next occurrence of character ch in strr
# starting from the given index
def nextOccurrence(strr, n, start, ch):
    for i in range(start, n):
 
        # Return the index of the first
        # occurrence of ch
        if (strr[i] == ch):
            return i
 
    # No occurrence found
    return -1
 
# Function to return the count of all
# the substrings of strr which contain
# the character ch at least one
def countSubStr(strr, n, ch):
 
    # To store the count of valid substrings
    cnt = 0
 
    # Index of the first occurrence of ch in strr
    j = nextOccurrence(strr, n, 0, ch)
 
    for i in range(n):
        while (j != -1 and j < i):
            j = nextOccurrence(strr, n, j + 1, ch)
 
        # No occurrence of ch after index i in strr
        if (j == -1):
            break
 
        # Substrings starting at index i
        # and ending at indices j, j+1, ..., n-1
        # are all valid substring
        cnt += (n - j)
 
    return cnt
 
# Driver code
strr = "geeksforgeeks"
n = len(strr)
ch = 'k'
 
print(countSubStr(strr, n, ch))
 
# This code is contributed by Mohit Kumar
 
 

C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    // Function to return the index of the
    // next occurrence of character ch in str
    // starting from the given index
    static int nextOccurrence(String str, int n,
                               int start, char ch)
    {
        for (int i = start; i < n; i++)
        {
     
            // Return the index of the first
            // occurrence of ch
            if (str[i] == ch)
                return i;
        }
     
        // No occurrence found
        return -1;
    }
     
    // Function to return the count of all
    // the substrings of str which contain
    // the character ch at least one
    static int countSubStr(String str,
                           int n, char ch)
    {
     
        // To store the count of valid substrings
        int cnt = 0;
     
        // Index of the first occurrence of ch in str
        int j = nextOccurrence(str, n, 0, ch);
        for (int i = 0; i < n; i++)
        {
            while (j != -1 && j < i)
            {
                j = nextOccurrence(str, n, j + 1, ch);
            }
     
            // No occurrence of ch after index i in str
            if (j == -1)
                break;
     
            // Substrings starting at index i
            // and ending at indices j, j+1, ..., n-1
            // are all valid substring
            cnt += (n - j);
        }
        return cnt;
    }
     
    // Driver code
    static public void Main ()
    {
        String str = "geeksforgeeks";
        int n = str.Length;
        char ch = 'k';
         
        Console.WriteLine(countSubStr(str, n, ch));
    }
}
 
// This code is contributed by AnkitRai01
 
 

Javascript




<script>
      // JavaScript implementation of the approach
      // Function to return the index of the
      // next occurrence of character ch in str
      // starting from the given index
      function nextOccurrence(str, n, start, ch) {
        for (var i = start; i < n; i++) {
          // Return the index of the first
          // occurrence of ch
          if (str[i] === ch) return i;
        }
 
        // No occurrence found
        return -1;
      }
 
      // Function to return the count of all
      // the substrings of str which contain
      // the character ch at least one
      function countSubStr(str, n, ch) {
        // To store the count of valid substrings
        var cnt = 0;
 
        // Index of the first occurrence of ch in str
        var j = nextOccurrence(str, n, 0, ch);
        for (var i = 0; i < n; i++) {
          while (j !== -1 && j < i) {
            j = nextOccurrence(str, n, j + 1, ch);
          }
 
          // No occurrence of ch after index i in str
          if (j === -1) break;
 
          // Substrings starting at index i
          // and ending at indices j, j+1, ..., n-1
          // are all valid substring
          cnt += n - j;
        }
        return cnt;
      }
 
      // Driver code
      var str = "geeksforgeeks";
      var n = str.length;
      var ch = "k";
 
      document.write(countSubStr(str, n, ch));
    </script>
 
 
Output: 
56

 



Next Article
Count substrings with k distinct characters

P

PrashantYadav6
Improve
Article Tags :
  • Algorithms
  • Analysis of Algorithms
  • DSA
  • Strings
  • substring
Practice Tags :
  • Algorithms
  • Strings

Similar Reads

  • Count of substrings having all distinct characters
    Given a string str consisting of lowercase alphabets, the task is to find the number of possible substrings (not necessarily distinct) that consists of distinct characters only.Examples: Input: Str = "gffg" Output: 6 Explanation: All possible substrings from the given string are, ( "g", "gf", "gff",
    7 min read
  • Count substrings with k distinct characters
    Given a string consisting of lowercase characters and an integer k, the task is to count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Examples: Input: s = "abc", k = 2Output: 2Explanation: Possible substrings are {"ab", "bc"} Input: s = "aba", k = 2Outp
    10 min read
  • Count number of substrings having at least K distinct characters
    Given a string S consisting of N characters and a positive integer K, the task is to count the number of substrings having at least K distinct characters. Examples: Input: S = "abcca", K = 3Output: 4Explanation:The substrings that contain at least K(= 3) distinct characters are: "abc": Count of dist
    7 min read
  • Count of all unique substrings with non-repeating characters
    Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
    6 min read
  • Count substrings made up of a single distinct character
    Given a string S of length N, the task is to count the number of substrings made up of a single distinct character.Note: For the repetitive occurrences of the same substring, count all repetitions. Examples: Input: str = "geeksforgeeks"Output: 15Explanation: All substrings made up of a single distin
    5 min read
  • Number of substrings with count of each character as k
    Given a string and an integer k, find the number of substrings in which all the different characters occur exactly k times. Examples: Input : s = "aabbcc" k = 2 Output : 6 The substrings are aa, bb, cc, aabb, bbcc and aabbcc. Input : s = "aabccc" k = 2 Output : 3 There are three substrings aa, cc an
    15 min read
  • Length of longest substring having all characters as K
    Given a string S and a character K. The task is to find the length of the longest substring of S having all characters the same as character K. Examples: Input: S = "abcd1111aabc", K = '1' Output: 4 Explanation: 1111 is the largest substring of length 4. Input: S = "#1234#@@abcd", K = '@' Output: 2
    8 min read
  • Count substrings with same first and last characters
    Given a string s consisting of lowercase characters, the task is to find the count of all substrings that start and end with the same character. Examples : Input : s = "abcab"Output : 7Explanation: The substrings are "a", "abca", "b", "bcab", "c", "a", "b".Input : s = "aba"Output : 4Explanation: The
    7 min read
  • Count of substrings which contains a given character K times
    Given a string consisting of numerical alphabets, a character C and an integer K, the task is to find the number of possible substrings which contains the character C exactly K times. Examples: Input : str = "212", c = '2', k = 1 Output : 4 Possible substrings are {"2", "21", "12", "2"} that contain
    9 min read
  • Count substrings with different first and last characters
    Given a string S, the task is to print the count of substrings from a given string whose first and last characters are different. Examples: Input: S = "abcab"Output: 8Explanation: There are 8 substrings having first and last characters different {ab, abc, abcab, bc, bca, ca, cab, ab}. Input: S = "ab
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences