Minimum value of K such that each substring of size K has the given character | C ++ program for the above approach ; Function to find the minimum value of K such that char c occurs in all K sized substrings of string S ; Store the string length ; Store difference of lengths of segments of every two consecutive occurrences of c ; Stores the maximum difference ; Store the previous occurence of char c ; Check if the current character is c or not ; Stores the difference of consecutive occurrences of c ; Update previous occurrence of c with current occurence ; Comparing diff with max ; If string doesn 't contain c ; Return max ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int findK ( string s , char c ) { int n = s . length ( ) ; int diff ; int max = 0 ; int prev = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( s [ i ] == c ) { diff = i - prev ; prev = i ; if ( diff > max ) { max = diff ; } } } if ( max == 0 ) return -1 ; return max ; } int main ( ) { string S = " abdegb " ; char ch = ' b ' ; cout << findK ( S , ch ) ; return 0 ; }