Problem Description
A teacher is writing a test with n true/false questions. The teacher wants to maximize the number of consecutive questions with the same answer to confuse the students. You are given a string answerKey, where answerKey[i] represents the original answer for question i, and an integer k which is the maximum number of changes you can perform (changing any answer to 'T' or 'F'). The task is to return the maximum number of consecutive 'T's or 'F's obtainable after performing at most k operations.
Key Insights
- The problem uses a sliding window to find the longest subarray where we can flip at most k characters.
- You calculate the maximum window length for both target characters 'T' and 'F' separately.
- Within the window, count the number of flips (i.e., the characters that are not the target).
- If the flip count exceeds k, slide the window from the left until the count is at most k.
- The answer is the maximum length among the two computed values.
Space and Time Complexity
Time Complexity: O(n) – We traverse the string possibly twice (once per target character). Space Complexity: O(1) – Only constant extra space is used.
Solution
We solve the problem using a sliding window approach. Two helper functions (or one function called twice) evaluate the maximum consecutive sequence for target characters 'T' and 'F'. For each target, expand the window by moving the right pointer and count flips (non-target characters). When the count exceeds k, move the left pointer to shrink the window until the count is within the limit. The maximum window size found is the answer. Finally, return the maximum from evaluating both targets.