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 Ktimes.

Examples:

Input : str = "212", c = '2', k = 1 
Output : 4
Possible substrings are {"2", "21", "12", "2"}
that contains 2 exactly 1 time.

Input  : str = "55555", c = '5', k = 4
Output : 2
Possible substrings are {"5555", "5555"} 
that contains 5 exactly 4 times

Naive Approach: A simple solution is to generate all the substrings of string and count the number of substrings in which given character occurs exactly k times.



The time complexity of this solution is O(N2) where N is the length of the string.

Efficient Approach: An efficient solution is to use sliding window technique. Find the substring that contains character C exactly K times starting with character C. Count the number of characters on either side of the substring. Multiply the counts to get the number of possible substrings with given substring

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to count the number of substrings
// which contains the character C exactly K times
  
#include <bits/stdc++.h>
using namespace std;
  
// Function to count the number of substrings
// which contains the character C exactly K times
int countSubString(string s, char c, int k)
{
    // left and right counters for characters on
    // both sides of substring window
    int leftCount = 0, rightCount = 0;
  
    // left and right pointer on both sides
    // of substring window
    int left = 0, right = 0;
  
    // intialize the frequency
    int freq = 0;
  
    // result and length of string
    int result = 0, len = s.length();
  
    // initialize the left pointer
    while (s[left] != c && left < len) {
        left++;
        leftCount++;
    }
  
    // initialize the right pointer
    right = left + 1;
    while (freq != (k - 1) && (right - 1) < len) {
        if (s[right] == c)
            freq++;
        right++;
    }
  
    // traverse all the window substrings
    while (left < len && (right - 1) < len) {
  
        // counting the characters on leftSide
        // of substring window
        while (s[left] != c && left < len) {
            left++;
            leftCount++;
        }
  
        // counting the characters on rightSide of
        // substring window
        while (right < len && s[right] != c) {
            if (s[right] == c)
                freq++;
            right++;
            rightCount++;
        }
  
        // Add the possible substrings on both
        // sides to result
        result = result + (leftCount + 1) * (rightCount + 1);
  
        // Setting the frequency for next
        // substring window
        freq = k - 1;
  
        // reset the left, right counters
        leftCount = 0;
        rightCount = 0;
  
        left++;
        right++;
    }
  
    return result;
}
  
// Driver code
int main()
{
    string s = "3123231";
    char c = '3';
    int k = 2;
  
    cout << countSubString(s, c, k);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count the number of substrings 
// which contains the character C exactly K times 
class GFG 
{
  
    // Function to count the number of substrings 
    // which contains the character C exactly K times 
    static int countSubString(String s, char c, int k) 
    {
        // left and right counters for characters on 
        // both sides of substring window 
        int leftCount = 0, rightCount = 0;
  
        // left and right pointer on both sides 
        // of substring window 
        int left = 0, right = 0;
  
        // intialize the frequency 
        int freq = 0;
  
        // result and length of string 
        int result = 0, len = s.length();
  
        // initialize the left pointer 
        while (s.charAt(left) != c && left < len) 
        {
            left++;
            leftCount++;
        }
  
        // initialize the right pointer 
        right = left + 1;
        while (freq != (k - 1) && (right - 1) < len) 
        {
            if (s.charAt(right) == c)
            {
                freq++;
            }
            right++;
        }
  
        // traverse all the window substrings 
        while (left < len && (right - 1) < len)
        {
  
            // counting the characters on leftSide 
            // of substring window 
            while (s.charAt(left) != c && left < len) 
            {
                left++;
                leftCount++;
            }
  
            // counting the characters on rightSide of 
            // substring window 
            while (right < len && s.charAt(right) != c)
            {
                if (s.charAt(right) == c)
                {
                    freq++;
                }
                right++;
                rightCount++;
            }
  
            // Add the possible substrings on both 
            // sides to result 
            result = result + (leftCount + 1) * (rightCount + 1);
  
            // Setting the frequency for next 
            // substring window 
            freq = k - 1;
  
            // reset the left, right counters 
            leftCount = 0;
            rightCount = 0;
  
            left++;
            right++;
        }
  
        return result;
    }
  
    // Driver code
    public static void main(String args[]) 
    {
        String s = "3123231";
        char c = '3';
        int k = 2;
  
        System.out.println(countSubString(s, c, k));
    }
}
  
/* This code is contributed by PrinciRaj1992 */

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to count the number of substrings
# which contains the character C exactly K times
  
# Function to count the number of substrings
# which contains the character C exactly K times
def countSubString(s, c, k):
  
    # left and right counters for characters 
    # on both sides of subwindow
    leftCount = 0
    rightCount = 0
  
    # left and right poer on both sides
    # of subwindow
    left = 0
    right = 0
  
    # ialize the frequency
    freq = 0
  
    # result and Length of string
    result = 0
    Len = len(s)
  
    # initialize the left poer
    while (s[left] != c and left < Len):
        left += 1
        leftCount += 1
  
    # initialize the right poer
    right = left + 1
    while (freq != (k - 1) and (right - 1) < Len):
        if (s[right] == c):
            freq += 1
        right += 1
  
    # traverse all the window substrings
    while (left < Len and (right - 1) < Len):
  
        # counting the characters on leftSide
        # of subwindow
        while (s[left] != c and left < Len):
            left += 1
            leftCount += 1
              
        # counting the characters on rightSide of
        # subwindow
        while (right < Len and s[right] != c):
            if (s[right] == c):
                freq += 1
            right += 1
            rightCount += 1
  
        # Add the possible substrings on both
        # sides to result
        result = (result + (leftCount + 1) * 
                           (rightCount + 1))
  
        # Setting the frequency for next
        # subwindow
        freq = k - 1
  
        # reset the left, right counters
        leftCount = 0
        rightCount = 0
  
        left += 1
        right += 1
  
    return result
  
# Driver code
s = "3123231"
c = '3'
k = 2
  
print(countSubString(s, c, k))
  
# This code is contributed by Mohit Kumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count the number of substrings 
// which contains the character C exactly K times 
using System;
  
class GFG
{
          
    // Function to count the number of substrings 
    // which contains the character C exactly K times 
    static int countSubString(string s, char c, int k) 
    
        // left and right counters for characters on 
        // both sides of substring window 
        int leftCount = 0, rightCount = 0; 
      
        // left and right pointer on both sides 
        // of substring window 
        int left = 0, right = 0; 
      
        // intialize the frequency 
        int freq = 0; 
      
        // result and length of string 
        int result = 0, len = s.Length; 
      
        // initialize the left pointer 
        while (s[left] != c && left < len) 
        
            left++; 
            leftCount++; 
        
      
        // initialize the right pointer 
        right = left + 1; 
        while (freq != (k - 1) && (right - 1) < len) 
        
            if (s[right] == c) 
                freq++; 
            right++; 
        
      
        // traverse all the window substrings 
        while (left < len && (right - 1) < len)
        
      
            // counting the characters on leftSide 
            // of substring window 
            while (s[left] != c && left < len) 
            
                left++; 
                leftCount++; 
            
      
            // counting the characters on rightSide of 
            // substring window 
            while (right < len && s[right] != c) 
            
                if (s[right] == c) 
                    freq++; 
                right++; 
                rightCount++; 
            
      
            // Add the possible substrings on both 
            // sides to result 
            result = result + (leftCount + 1) * (rightCount + 1); 
      
            // Setting the frequency for next 
            // substring window 
            freq = k - 1; 
      
            // reset the left, right counters 
            leftCount = 0; 
            rightCount = 0; 
      
            left++; 
            right++; 
        
      
        return result; 
    
      
    // Driver code 
    static public void Main () 
    
        string s = "3123231"
        char c = '3'
        int k = 2; 
      
        Console.WriteLine(countSubString(s, c, k)); 
    }
}
  
// This code is contributed by AnkitRai01

chevron_right


Output:

8

Time Complexity: O(N)



My Personal Notes arrow_drop_up

Always try to improve and willing to learn

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.