Substring of length K having maximum frequency in the given string | C ++ program for the above approach ; Function that generates substring of length K that occurs maximum times ; Store the frequency of substrings ; Deque to maintain substrings window size K ; Update the frequency of the first substring in the Map ; Remove the first character of the previous K length substring ; Traverse the string ; Insert the current character as last character of current substring ; Pop the first character of previous K length substring ; Find the substring that occurs maximum number of times ; Print the substring ; Driver Code ; Given string ; Given K size of substring ; Function Call
#include <bits/stdc++.h> NEW_LINE using ll = long long int ; using namespace std ; void maximumOccurringString ( string s , ll K ) { map < deque < char > , ll > M ; ll i ; deque < char > D ; for ( i = 0 ; i < K ; i ++ ) { D . push_back ( s [ i ] ) ; } M [ D ] ++ ; D . pop_front ( ) ; for ( ll j = i ; j < s . size ( ) ; j ++ ) { D . push_back ( s [ j ] ) ; M [ D ] ++ ; D . pop_front ( ) ; } ll maxi = INT_MIN ; deque < char > ans ; for ( auto it : M ) { if ( it . second > maxi ) { maxi = it . second ; ans = it . first ; } } for ( ll i = 0 ; i < ans . size ( ) ; i ++ ) { cout << ans [ i ] ; } } int main ( ) { string s = " bbbbbaaaaabbabababa " ; ll K = 5 ; maximumOccurringString ( s , K ) ; return 0 ; }