Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Is this a bug in the algorithm?

sw94070

Mar 27, 2025

In the shrinking window part:

        // current window size is from windowStart to windowEnd, overall we have a letter
        // which is repeating 'maxRepeatLetterCount' times, this means we can have a window
        // which has one letter repeating 'maxRepeatLetterCount' times and the remaining
        // letters we should replace. If the remaining letters are more than 'k', it is the
        // time to shrink the window as we are not allowed to replace more than 'k' letters
        if (windowEnd - windowStart + 1 - maxRepeatLetterCount > k) {
            char leftChar = str.charAt(windowStart);
            letterFrequencyMap.put(leftChar, letterFrequencyMap.get(leftChar) - 1);
            windowStart++;
        }

What if the chatAt(windowStart) is a maxRepeatLetter? After removing windowStart character, we still have more than k letter to be replaced, because removing a maxRepeatLetter reduces the macRepeatLetterCount. So in this case, the next step calculating maxLength is not correct, because this substring [windowStart, windowEnd] would require more than k letters to be replaced. Am I missing something? Thanks.

3

0

Comments
Comments
Harman Tatla
Harman Tatla6 months ago

This is a bug, the if should be a while loop and you'll need to recompute the most frequently occurring char each time (you can simply do a linear lookup since it will be O(1) as the set of distinct chars is just the lower case english alphabet i.e. 26 chars).

Consider...

On this page