Count substrings with each character occurring at most k times | CPP program to count number of substrings in which each character has count less than or equal to k . ; function to find number of substring in which each character has count less than or equal to k . ; initialize left and right pointer to 0 ; an array to keep track of count of each alphabet ; decrement the count ; increment left pointer ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find_sub ( string s , int k ) { int len = s . length ( ) ; int lp = 0 , rp = 0 ; int ans = 0 ; int hash_char [ 26 ] = { 0 } ; for ( ; rp < len ; rp ++ ) { hash_char [ s [ rp ] - ' a ' ] ++ ; while ( hash_char [ s [ rp ] - ' a ' ] > k ) { hash_char [ s [ lp ] - ' a ' ] -- ; lp ++ ; } ans += rp - lp + 1 ; } return ans ; } int main ( ) { string s = " aaabb " ; int k = 2 ; cout << find_sub ( s , k ) << endl ; }