Count substrings with each character occurring at most k times
Given a string S. Count number of substrings in which each character occurs at most k times. Assume that the string consists of only lowercase English alphabets.
Examples:
Input : S = ab k = 1 Output : 3 All the substrings a, b, ab have individual character count less than 1. Input : S = aaabb k = 2 Output : 12 Substrings that have individual character count at most 2 are: a, a, a, b, b, aa, aa, ab, bb, aab, abb, aabb.
Brute Force Approach:
A simple solution is to first find all the substrings and then check if the count of each character is at most k in each substring. The time complexity of this solution is O(n^3). We can check all the possible substrings ranges from i to j and in this substring we have to check whether the maximum frequency is greater than k or not.if it is less than or equal to k then count this substring in ans .
C++
// CPP program to count number of substrings // in which each character has count less // than or equal to k. #include <bits/stdc++.h> using namespace std; int findSubstrings(string s, int k) { // int i, j, n = s.length(); // variable to store count of substrings. // Total non empty substring n*(n+1) /2. int ans = n * (n + 1) / 2; for (i = 0; i < n; i++) { for (j = i; j < n; j++) { bool flag = false ; // hash map storing maximum frequency of each // character. unordered_map< int , int > m; for ( int l = i; l <= j; l++) { m[s[l]]++; if (m[s[l]] > k) { ans--; break ; flag = true ; } } } } // return the final count of substrings. return ans; } // Driver code int main() { string S = "aaabb" ; int k = 2; cout << findSubstrings(S, k); return 0; } |
Java
/*package whatever //do not write package name here */ import java.io.*; import java.util.*; // java code addition public class Main { // Javat program to count number of substrings // in which each character has count less // than or equal to k. public static int findSubstrings(String s, int k) { int n = s.length(); // variable to store count of substrings. // Total non empty substring n*(n+1) /2. int ans = ( int )Math.floor((n * (n + 1 )) / 2 ); for ( int i = 0 ; i < n; i++) { for ( int j = i; j < n; j++) { boolean flag = false ; // hash map storing maximum frequency of each // character. Map<Character,Integer> m= new HashMap<Character,Integer>(); for ( int l = i; l <= j; l++) { if (m.containsKey(s.charAt(l))){ m.put(s.charAt(l), m.get(s.charAt(l)) + 1 ); } else { m.put(s.charAt(l), 1 ); } if (m.get(s.charAt(l)) > k) { ans--; break ; } } if (flag) { break ; } } } // return the final count of substrings. return ans; } public static void main(String[] args) { String S = "aaabb" ; int k = 2 ; System.out.println(findSubstrings(S, k)); } } // The code is contributed by Arushi Jindal. |
Python3
# Python program to count number of substrings # in which each character has count less # than or equal to k. def find_substrings(s, k): # Get the length of the string n = len (s) # Initialize the variable to store the count of substrings ans = n * (n + 1 ) / / 2 # Iterate through all possible substrings for i in range (n): for j in range (i, n): # Initialize a frequency list to store the count of each character freq = [ 0 ] * 26 # Count the frequency of each character in the current substring for l in range (i, j + 1 ): freq[ ord (s[l]) - ord ( 'a' )] + = 1 # If any character occurs more than k times, subtract 1 from the count of substrings if max (freq) > k: ans - = 1 break # Return the final count of substrings return ans # Example usage S = "aaabb" k = 2 print (find_substrings(S, k)) # Output: 12 |
C#
using System; using System.Collections.Generic; public class Gfg { public static int findSubstrings( string s, int k) { int n = s.Length; int ans = n * (n + 1) / 2; for ( int i = 0; i < n; i++) { for ( int j = i; j < n; j++) { bool flag = false ; Dictionary< char , int > m = new Dictionary< char , int >(); for ( int l = i; l <= j; l++) { if (m.ContainsKey(s[l])) m[s[l]]++; else m[s[l]] = 1; if (m[s[l]] > k) { ans--; break ; flag = true ; } } if (flag) break ; } } return ans; } public static void Main() { string S = "aaabb" ; int k = 2; Console.WriteLine(findSubstrings(S, k)); } } |
Javascript
// JavaScript program to count number of substrings // in which each character has count less // than or equal to k. function findSubstrings(s, k) { const n = s.length; // variable to store count of substrings. // Total non empty substring n*(n+1) /2. let ans = Math.floor((n * (n + 1)) / 2); for (let i = 0; i < n; i++) { for (let j = i; j < n; j++) { let flag = false ; // hash map storing maximum frequency of each // character. const m = new Map(); for (let l = i; l <= j; l++) { m.set(s[l], (m.get(s[l]) || 0) + 1); if (m.get(s[l]) > k) { ans--; break ; flag = true ; } } if (flag) { break ; } } } // return the final count of substrings. return ans; } const S = 'aaabb' ; const k = 2; console.log(findSubstrings(S, k)); |
12
Time Complexity:O(N3), where N is the length of the string
Space Complexity : O(N), where N is the length of the string
An efficient solution is to maintain starting and ending point of substrings. Let us fix the starting point to an index i. Keep incrementing the ending point j one at a time. When changing the ending point update the count of corresponding character. Then check for this substring that whether each character has count at most k or not. If yes then increment answer by 1 else increment the starting point and reset ending point.
The starting point is incremented because during last update on ending point character count exceed k and it will only increase further. So no subsequent substring with given fixed starting point will be a substring with each character count at most k.
Implementation:
C++
// CPP program to count number of substrings // in which each character has count less // than or equal to k. #include <bits/stdc++.h> using namespace std; int findSubstrings(string s, int k) { // variable to store count of substrings. int ans = 0; // array to store count of each character. int cnt[26]; int i, j, n = s.length(); for (i = 0; i < n; i++) { // Initialize all characters count to zero. memset (cnt, 0, sizeof (cnt)); for (j = i; j < n; j++) { // increment character count cnt[s[j] - 'a' ]++; // check only the count of current character // because only the count of this // character is changed. The ending point is // incremented to current position only if // all other characters have count at most // k and hence their count is not checked. // If count is less than k, then increase ans // by 1. if (cnt[s[j] - 'a' ] <= k) ans++; // if count is less than k, then break as // subsequent substrings for this starting // point will also have count greater than // k and hence are reduntant to check. else break ; } } // return the final count of substrings. return ans; } // Driver code int main() { string S = "aaabb" ; int k = 2; cout << findSubstrings(S, k); return 0; } |
Java
import java.util.Arrays; // Java program to count number of substrings // in which each character has count less // than or equal to k. class GFG { static int findSubstrings(String s, int k) { // variable to store count of substrings. int ans = 0 ; // array to store count of each character. int cnt[] = new int [ 26 ]; int i, j, n = s.length(); for (i = 0 ; i < n; i++) { // Initialize all characters count to zero. Arrays.fill(cnt, 0 ); for (j = i; j < n; j++) { // increment character count cnt[s.charAt(j) - 'a' ]++; // check only the count of current character // because only the count of this // character is changed. The ending point is // incremented to current position only if // all other characters have count at most // k and hence their count is not checked. // If count is less than k, then increase ans // by 1. if (cnt[s.charAt(j) - 'a' ] <= k) { ans++; } // if count is less than k, then break as // subsequent substrings for this starting // point will also have count greater than // k and hence are reduntant to check. else { break ; } } } // return the final count of substrings. return ans; } // Driver code static public void main(String[] args) { String S = "aaabb" ; int k = 2 ; System.out.println(findSubstrings(S, k)); } } // This code is contributed by 29AjayKumar |
Python 3
# Python 3 program to count number of substrings # in which each character has count less # than or equal to k. def findSubstrings(s, k): # variable to store count of substrings. ans = 0 n = len (s) for i in range (n): # array to store count of each character. cnt = [ 0 ] * 26 for j in range (i, n): # increment character count cnt[ ord (s[j]) - ord ( 'a' )] + = 1 # check only the count of current character # because only the count of this # character is changed. The ending point is # incremented to current position only if # all other characters have count at most # k and hence their count is not checked. # If count is less than k, then increase # ans by 1. if (cnt[ ord (s[j]) - ord ( 'a' )] < = k): ans + = 1 # if count is less than k, then break as # subsequent substrings for this starting # point will also have count greater than # k and hence are reduntant to check. else : break # return the final count of substrings. return ans # Driver code if __name__ = = "__main__" : S = "aaabb" k = 2 print (findSubstrings(S, k)) # This code is contributed by ita_c |
C#
// C# program to count number of substrings // in which each character has count less // than or equal to k. using System; class GFG { public static int findSubstrings( string s, int k) { // variable to store count of substrings. int ans = 0; // array to store count of each character. int []cnt = new int [26]; int i, j, n = s.Length; for (i = 0; i < n; i++) { // Initialize all characters count to zero. Array.Clear(cnt, 0, cnt.Length); for (j = i; j < n; j++) { // increment character count cnt[s[j] - 'a' ]++; // check only the count of current character // because only the count of this // character is changed. The ending point is // incremented to current position only if // all other characters have count at most // k and hence their count is not checked. // If count is less than k, then increase ans // by 1. if (cnt[s[j] - 'a' ] <= k) ans++; // if count is less than k, then break as // subsequent substrings for this starting // point will also have count greater than // k and hence are reduntant to check. else break ; } } // return the final count of substrings. return ans; } // Driver code public static int Main() { string S = "aaabb" ; int k = 2; Console.WriteLine(findSubstrings(S, k)); return 0; } } // This code is contributed by SoM15242. |
Javascript
<script> // Javascript program to count number of substrings // in which each character has count less // than or equal to k. function findSubstrings(s, k) { // variable to store count of substrings. var ans = 0; // array to store count of each character. var cnt = Array(26); var i, j, n = s.length; for (i = 0; i < n; i++) { cnt = Array(26).fill(0); for (j = i; j < n; j++) { // increment character count cnt[(s[j].charCodeAt(0) - 'a' .charCodeAt(0))]++; // check only the count of current character // because only the count of this // character is changed. The ending point is // incremented to current position only if // all other characters have count at most // k and hence their count is not checked. // If count is less than k, then increase ans // by 1. if (cnt[(s[j].charCodeAt(0) - 'a' .charCodeAt(0))] <= k) ans++; // if count is less than k, then break as // subsequent substrings for this starting // point will also have count greater than // k and hence are reduntant to check. else break ; } } // return the final count of substrings. return ans; } // Driver code var S = "aaabb" ; var k = 2; document.write( findSubstrings(S, k)); // This code is contributed by rrrtnx. </script> |
12
Time complexity: O(n^2)
Auxiliary Space: O(1)
Another efficient solution is to use sliding window technique. In which we will maintain two pointers left and right.We initialize left and the right pointer to 0, move the right pointer until the count of each alphabet is less than k, when the count is greater than we start incrementing left pointer and decrement the count of the corresponding alphabet, once the condition is satisfied we add (right-left + 1) to the answer.
Implementation:
C++
// CPP program to count number of substrings // in which each character has count less // than or equal to k. #include<bits/stdc++.h> using namespace std; //function to find number of substring //in which each character has count less // than or equal to k. int find_sub(string s, int k){ int len=s.length(); int lp=0,rp=0; // initialize left and right pointer to 0 int ans=0; int hash_char[26]={0}; // an array to keep track of count of each alphabet for (;rp<len;rp++){ hash_char[s[rp]- 'a' ]++; while (hash_char[s[rp]- 'a' ]>k){ hash_char[s[lp]- 'a' ]--; // decrement the count lp++; //increment left pointer } ans+=rp-lp+1; } return ans; } // Driver code int main(){ string s= "aaabb" ; int k=2; cout<<find_sub(s,k)<<endl; } |
Java
// Java program to count number of substrings // in which each character has count less // than or equal to k. class GFG { //function to find number of substring //in which each character has count less // than or equal to k. static int find_sub(String s, int k) { int len = s.length(); // initialize left and right pointer to 0 int lp = 0 , rp = 0 ; int ans = 0 ; // an array to keep track of count of each alphabet int [] hash_char = new int [ 26 ]; for (; rp < len; rp++) { hash_char[s.charAt(rp) - 'a' ]++; while (hash_char[s.charAt(rp) - 'a' ] > k) { // decrement the count hash_char[s.charAt(lp) - 'a' ]--; //increment left pointer lp++; } ans += rp - lp + 1 ; } return ans; } // Driver code public static void main(String[] args) { String S = "aaabb" ; int k = 2 ; System.out.println(find_sub(S, k)); } } // This code is contributed by PrinciRaj1992 |
Python
# Python3 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. def find_sub(s, k): Len = len (s) # initialize left and right pointer to 0 lp, rp = 0 , 0 ans = 0 # an array to keep track of count of each alphabet hash_char = [ 0 for i in range ( 256 )] for rp in range ( Len ): hash_char[ ord (s[rp])] + = 1 while (hash_char[ ord (s[rp])] > k): hash_char[ ord (s[lp])] - = 1 # decrement the count lp + = 1 #increment left pointer ans + = rp - lp + 1 return ans # Driver code s = "aaabb" k = 2 ; print (find_sub(s, k)) # This code is contributed by mohit kumar |
C#
// C# program to count number of substrings // in which each character has count less // than or equal to k. using System; class GFG { //function to find number of substring //in which each character has count less // than or equal to k. static int find_sub( string s, int k) { int len = s.Length; // initialize left and right pointer to 0 int lp = 0,rp = 0; int ans = 0; // an array to keep track of count of each alphabet int []hash_char = new int [26]; for (;rp < len; rp++) { hash_char[s[rp] - 'a' ]++; while (hash_char[s[rp] - 'a' ] > k) { // decrement the count hash_char[s[lp] - 'a' ]--; //increment left pointer lp++; } ans += rp - lp + 1; } return ans; } // Driver code static public void Main() { String S = "aaabb" ; int k = 2; Console.WriteLine(find_sub(S, k)); } } // This code is contributed by Rajput-Ji |
Javascript
<script> // Javascript 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. function find_sub(s,k) { let len = s.length; // initialize left and right pointer to 0 let lp = 0, rp = 0; let ans = 0; // an array to keep track of count of each alphabet let hash_char = new Array(26); for (let i = 0; i < hash_char.length; i++) { hash_char[i] = 0; } for (; rp < len; rp++) { hash_char[s[rp].charCodeAt(0) - 'a' .charCodeAt(0)]++; while (hash_char[s[rp].charCodeAt(0) - 'a' .charCodeAt(0)] > k) { // decrement the count hash_char[s[lp].charCodeAt(0) - 'a' .charCodeAt(0)]--; //increment left pointer lp++; } ans += rp - lp + 1; } return ans; } // Driver code let S = "aaabb" ; let k = 2; document.write(find_sub(S, k)); // This code is contributed by avanitrachhadiya2155 </script> |
12
Time complexity: O(n)
Auxiliary Space: O(1)