Leetcode 424: longest repeating character replacement

·

1 min read

I am writing this explanation, because I came across this question, and it has a really bad description, it is a sliding window problem, but the size of the window is reduced due to a specific condition that we will see in the code, no good explanation is present even though it is a simple question, a intuitive explanation is well needed for this question as it is a medium question.

class Solution:
    def characterReplacement(self, s: str, k: int) -> int:
        longest = 0
        l = 0
        counts = [0] * 26 # set for storing count of each type of letter in s

        for r in range(len(s)):
            counts[ord(s[r]) - 65] += 1 # incrementing count of letter at current
                                        # index
            while (r - l + 1) - max(counts) > k: 
            # checking if the  (current window size - most common element) is
            # greater than K, which makes our replacing condition False
                counts[ord(s[l]) - 65] -= 1 # decrement count of letter at l
                l += 1

            longest = max(longest, (r - l + 1))
        return longest