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 and cc
Naive Approach: The idea is to traverse through all substrings. We fix a starting point, traverse through all substrings starting with the picked point, we keep incrementing frequencies of all characters. If all frequencies become k, we increment the result. If the count of any frequency becomes more than k, we break and change starting point.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int MAX_CHAR = 26;
bool check( int freq[], int k)
{
for ( int i = 0; i < MAX_CHAR; i++)
if (freq[i] && freq[i] != k)
return false ;
return true ;
}
int substrings(string s, int k)
{
int res = 0;
for ( int i = 0; s[i]; i++) {
int freq[MAX_CHAR] = { 0 };
for ( int j = i; s[j]; j++) {
int index = s[j] - 'a' ;
freq[index]++;
if (freq[index] > k)
break ;
else if (freq[index] == k &&
check(freq, k) == true )
res++;
}
}
return res;
}
int main()
{
string s = "aabbcc" ;
int k = 2;
cout << substrings(s, k) << endl;
s = "aabbc" ;
k = 2;
cout << substrings(s, k) << endl;
}
|
Java
import java.io.*;
class GFG
{
static int MAX_CHAR = 26 ;
static boolean check( int freq[], int k)
{
for ( int i = 0 ; i < MAX_CHAR; i++)
if (freq[i] != 0 && freq[i] != k)
return false ;
return true ;
}
static int substrings(String s, int k)
{
int res = 0 ;
for ( int i = 0 ; i< s.length(); i++)
{
int freq[] = new int [MAX_CHAR];
for ( int j = i; j<s.length(); j++)
{
int index = s.charAt(j) - 'a' ;
freq[index]++;
if (freq[index] > k)
break ;
else if (freq[index] == k &&
check(freq, k) == true )
res++;
}
}
return res;
}
public static void main(String[] args)
{
String s = "aabbcc" ;
int k = 2 ;
System.out.println(substrings(s, k));
s = "aabbc" ;
k = 2 ;
System.out.println(substrings(s, k));
}
}
|
Python3
MAX_CHAR = 26
def check(freq, k):
for i in range ( 0 , MAX_CHAR):
if (freq[i] and freq[i] ! = k):
return False
return True
def substrings(s, k):
res = 0
for i in range ( 0 , len (s)):
freq = [ 0 ] * MAX_CHAR
for j in range (i, len (s)):
index = ord (s[j]) - ord ( 'a' )
freq[index] + = 1
if (freq[index] > k):
break
elif (freq[index] = = k and
check(freq, k) = = True ):
res + = 1
return res
if __name__ = = "__main__" :
s = "aabbcc"
k = 2
print (substrings(s, k))
s = "aabbc" ;
k = 2 ;
print (substrings(s, k))
|
C#
using System;
class GFG
{
static int MAX_CHAR = 26;
static bool check( int []freq, int k)
{
for ( int i = 0; i < MAX_CHAR; i++)
if (freq[i] != 0 && freq[i] != k)
return false ;
return true ;
}
static int substrings(String s, int k)
{
int res = 0;
for ( int i = 0; i < s.Length; i++)
{
int []freq = new int [MAX_CHAR];
for ( int j = i; j < s.Length; j++)
{
int index = s[j] - 'a' ;
freq[index]++;
if (freq[index] > k)
break ;
else if (freq[index] == k &&
check(freq, k) == true )
res++;
}
}
return res;
}
public static void Main(String[] args)
{
String s = "aabbcc" ;
int k = 2;
Console.WriteLine(substrings(s, k));
s = "aabbc" ;
k = 2;
Console.WriteLine(substrings(s, k));
}
}
|
PHP
<?php
$MAX_CHAR = 26;
function check(& $freq , $k )
{
global $MAX_CHAR ;
for ( $i = 0; $i < $MAX_CHAR ; $i ++)
if ( $freq [ $i ] && $freq [ $i ] != $k )
return false;
return true;
}
function substrings( $s , $k )
{
global $MAX_CHAR ;
$res = 0;
for ( $i = 0; $i < strlen ( $s ); $i ++)
{
$freq = array_fill (0, $MAX_CHAR ,NULL);
for ( $j = $i ; $j < strlen ( $s ); $j ++)
{
$index = ord( $s [ $j ]) - ord( 'a' );
$freq [ $index ]++;
if ( $freq [ $index ] > $k )
break ;
else if ( $freq [ $index ] == $k &&
check( $freq , $k ) == true)
$res ++;
}
}
return $res ;
}
$s = "aabbcc" ;
$k = 2;
echo substrings( $s , $k ). "\n" ;
$s = "aabbc" ;
$k = 2;
echo substrings( $s , $k ). "\n" ;
?>
|
Javascript
<script>
let MAX_CHAR = 26;
function check(freq,k)
{
for (let i = 0; i < MAX_CHAR; i++)
if (freq[i] != 0 && freq[i] != k)
return false ;
return true ;
}
function substrings(s, k)
{
let res = 0;
for (let i = 0; i< s.length; i++)
{
let freq = new Array(MAX_CHAR);
for (let i = 0; i < freq.length ;i++)
{
freq[i] = 0;
}
for (let j = i; j < s.length; j++)
{
let index = s[j].charCodeAt(0) -
'a' .charCodeAt(0);
freq[index]++;
if (freq[index] > k)
break ;
else if (freq[index] == k &&
check(freq, k) == true )
res++;
}
}
return res;
}
let s = "aabbcc" ;
let k = 2;
document.write(substrings(s, k) + "<br>" );
s = "aabbc" ;
k = 2;
document.write(substrings(s, k) + "<br>" );
</script>
|
Time Complexity: O(n*n) where n is the length of input string. Function Check() is running a loop of constant length from 0 to MAX_CHAR (ie; 26 always) so this function check() is running in O(MAX_CHAR) time so Time complexity is O(MAX_CHAR*n*n)=O(n^2).
Auxiliary Space: O(1)
Efficient Approach: On very careful observation, we can see that it is enough to check the same for substrings of length
where
is the number of distinct characters present in the given string.
Argument:
Consider a substring S_{i+1}S_{i+2}\dots S_{i+p} of length ‘p’. If this substring has ‘m’ distinct characters and each distinct character occurs exactly ‘K’ times, then the length of the substring, ‘p’, is given by p = K\times m. Since ‘
‘ is always a multiple of ‘K’ and
for the given string, it is enough to iterate over the substrings whose length is divisible by ‘K’ and having m, 1 \le m \le 26 distinct characters. We will use Sliding window to iterate over the substrings of fixed length.
Solution:
- Find the number of distinct characters present in the given string. Let it be D.
- For each i, 1\le i\le D, do the following
- Iterate over the substrings of length $i \times K$, using a sliding window.
- Check if they satisfy the condition – All distinct characters in the substring occur exactly K times.
- If they satisfy the condition, increment the count.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <map>
#include <set>
#include <string>
int min( int a, int b) { return a < b ? a : b; }
using namespace std;
bool have_same_frequency(map< char , int >& freq, int k)
{
for ( auto & pair : freq) {
if (pair.second != k && pair.second != 0) {
return false ;
}
}
return true ;
}
int count_substrings(string s, int k)
{
int count = 0;
int distinct = (set< char >(s.begin(), s.end())).size();
for ( int length = 1; length <= distinct; length++) {
int window_length = length * k;
map< char , int > freq;
int window_start = 0;
int window_end = window_start + window_length - 1;
for ( int i = window_start;
i <= min(window_end, s.length() - 1); i++) {
freq[s[i]]++;
}
while (window_end < s.length()) {
if (have_same_frequency(freq, k)) {
count++;
}
freq[s[window_start]]--;
window_start++;
window_end++;
if (window_length < s.length()) {
freq[s[window_end]]++;
}
}
}
return count;
}
int main()
{
string s = "aabbcc" ;
int k = 2;
cout << count_substrings(s, k) << endl;
s = "aabbc" ;
k = 2;
cout << count_substrings(s, k) << endl;
return 0;
}
|
C
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
int min( int a, int b) { return a < b ? a : b; }
bool have_same_frequency( int freq[], int k)
{
for ( int i = 0; i < 26; i++) {
if (freq[i] != 0 && freq[i] != k) {
return false ;
}
}
return true ;
}
int count_substrings( char * s, int n, int k)
{
int count = 0;
int distinct = 0;
bool have[26] = { false };
for ( int i = 0; i < n; i++) {
have[s[i] - 'a' ] = true ;
}
for ( int i = 0; i < 26; i++) {
if (have[i]) {
distinct++;
}
}
for ( int length = 1; length <= distinct; length++) {
int window_length = length * k;
int freq[26] = { 0 };
int window_start = 0;
int window_end = window_start + window_length - 1;
for ( int i = window_start;
i <= min(window_end, n - 1); i++) {
freq[s[i] - 'a' ]++;
}
while (window_end < n) {
if (have_same_frequency(freq, k)) {
count++;
}
freq[s[window_start] - 'a' ]--;
window_start++;
window_end++;
if (window_end < n) {
freq[s[window_end] - 'a' ]++;
}
}
}
return count;
}
int main()
{
char * s = "aabbcc" ;
int k = 2;
printf ( "%d\n" , count_substrings(s, 6, k));
s = "aabbc" ;
k = 2;
printf ( "%d\n" , count_substrings(s, 5, k));
return 0;
}
|
Java
import java.util.*;
class GFG {
static boolean have_same_frequency( int [] freq, int k)
{
for ( int i = 0 ; i < 26 ; i++) {
if (freq[i] != 0 && freq[i] != k) {
return false ;
}
}
return true ;
}
static int count_substrings(String s, int k)
{
int count = 0 ;
int distinct = 0 ;
boolean [] have = new boolean [ 26 ];
Arrays.fill(have, false );
for ( int i = 0 ; i < s.length(); i++) {
have[(( int )(s.charAt(i) - 'a' ))] = true ;
}
for ( int i = 0 ; i < 26 ; i++) {
if (have[i]) {
distinct++;
}
}
for ( int length = 1 ; length <= distinct; length++) {
int window_length = length * k;
int [] freq = new int [ 26 ];
Arrays.fill(freq, 0 );
int window_start = 0 ;
int window_end
= window_start + window_length - 1 ;
for ( int i = window_start;
i <= Math.min(window_end, s.length() - 1 );
i++) {
freq[(( int )(s.charAt(i) - 'a' ))]++;
}
while (window_end < s.length()) {
if (have_same_frequency(freq, k)) {
count++;
}
freq[(
( int )(s.charAt(window_start) - 'a' ))]--;
window_start++;
window_end++;
if (window_end < s.length()) {
freq[(( int )(s.charAt(window_end)
- 'a' ))]++;
}
}
}
return count;
}
public static void main(String[] args)
{
String s = "aabbcc" ;
int k = 2 ;
System.out.println(count_substrings(s, k));
s = "aabbc" ;
k = 2 ;
System.out.println(count_substrings(s, k));
}
}
|
Python3
from collections import defaultdict
def have_same_frequency(freq: defaultdict, k: int ):
return all ([freq[i] = = k or freq[i] = = 0 for i in freq])
def count_substrings(s: str , k: int ) - > int :
count = 0
distinct = len ( set ([i for i in s]))
for length in range ( 1 , distinct + 1 ):
window_length = length * k
freq = defaultdict( int )
window_start = 0
window_end = window_start + window_length - 1
for i in range (window_start, min (window_end + 1 , len (s))):
freq[s[i]] + = 1
while window_end < len (s):
if have_same_frequency(freq, k):
count + = 1
freq[s[window_start]] - = 1
window_start + = 1
window_end + = 1
if window_end < len (s):
freq[s[window_end]] + = 1
return count
if __name__ = = '__main__' :
s = "aabbcc"
k = 2
print (count_substrings(s, k))
s = "aabbc"
k = 2
print (count_substrings(s, k))
|
C#
using System;
class GFG{
static bool have_same_frequency( int [] freq, int k)
{
for ( int i = 0; i < 26; i++)
{
if (freq[i] != 0 && freq[i] != k)
{
return false ;
}
}
return true ;
}
static int count_substrings( string s, int k)
{
int count = 0;
int distinct = 0;
bool [] have = new bool [26];
Array.Fill(have, false );
for ( int i = 0; i < s.Length; i++)
{
have[(( int )(s[i] - 'a' ))] = true ;
}
for ( int i = 0; i < 26; i++)
{
if (have[i])
{
distinct++;
}
}
for ( int length = 1; length <= distinct; length++)
{
int window_length = length * k;
int [] freq = new int [26];
Array.Fill(freq, 0);
int window_start = 0;
int window_end = window_start +
window_length - 1;
for ( int i = window_start;
i <= Math.Min(window_end, s.Length - 1);
i++)
{
freq[(( int )(s[i] - 'a' ))]++;
}
while (window_end < s.Length)
{
if (have_same_frequency(freq, k))
{
count++;
}
freq[(( int )(s[window_start] - 'a' ))]--;
window_start++;
window_end++;
if (window_end < s.Length)
{
freq[(( int )(s[window_end] - 'a' ))]++;
}
}
}
return count;
}
public static void Main( string [] args)
{
string s = "aabbcc" ;
int k = 2;
Console.WriteLine(count_substrings(s, k));
s = "aabbc" ;
k = 2;
Console.WriteLine(count_substrings(s, k));
}
}
|
Javascript
<script>
function have_same_frequency(freq,k)
{
for (let i = 0; i < 26; i++) {
if (freq[i] != 0 && freq[i] != k) {
return false ;
}
}
return true ;
}
function count_substrings(s,k)
{
let count = 0;
let distinct = 0;
let have = new Array(26);
for (let i=0;i<26;i++)
{
have[i]= false ;
}
for (let i = 0; i < s.length; i++) {
have[((s[i].charCodeAt(0) -
'a' .charCodeAt(0)))] = true ;
}
for (let i = 0; i < 26; i++) {
if (have[i]) {
distinct++;
}
}
for (let length = 1; length <= distinct; length++) {
let window_length = length * k;
let freq = new Array(26);
for (let i=0;i<26;i++)
freq[i]=0;
let window_start = 0;
let window_end
= window_start + window_length - 1;
for (let i = window_start;
i <= Math.min(window_end, s.length - 1);
i++) {
freq[((s[i].charCodeAt(0) -
'a' .charCodeAt(0)))]++;
}
while (window_end < s.length) {
if (have_same_frequency(freq, k)) {
count++;
}
freq[(
(s[window_start].charCodeAt(0) -
'a' .charCodeAt(0)))]--;
window_start++;
window_end++;
if (window_end < s.length) {
freq[(s[window_end].charCodeAt(0)
- 'a' .charCodeAt(0))]++;
}
}
}
return count;
}
let s = "aabbcc" ;
let k = 2;
document.write(count_substrings(s, k)+ "<br>" );
s = "aabbc" ;
k = 2;
document.write(count_substrings(s, k)+ "<br>" );
</script>
|
Time Complexity: O(N * D) where D is the number of distinct characters present in the string and N is the length of the string.
Auxiliary Space: O(N)
This article is contributed by Aarti_Rathi and Rahul Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...