educative.io

Educative

I have an alternate approach to this question

public static int findLength(String str, int k) {
int max = Integer.MIN_VALUE;
for(char c = ‘a’; c <= ‘z’; ++c){
int start = 0; int kdash = k;
for(int end = 0; end<str.length();end++){
if(str.charAt(end)!=c){
kdash–;
}
if(kdash<0){
if(str.charAt(start)!=c) kdash++;
start++;
}else max = Math.max(end-start+1, max);
}
}
return max;
}
By following this approach we are basically giving every character a chance to be selected as a replacement character and overall complexity still remains the same that is O(N) since outer loop is only of 26 length.

Hi @shubhankar_singh,
Thank you for reaching out to us. We appreciate learners who think creatively and provide alternative ideas. Your solution is working perfectly.
I hope Educative has helped you in your learning :slight_smile: