Maximize the Confusion of an Exam - Problem

A teacher is preparing a true/false exam to maximize student confusion by creating the longest possible sequence of consecutive identical answers. The exam consists of n questions, where each answer is either 'T' (True) or 'F' (False).

You are given a string answerKey representing the original answers, and an integer k representing the maximum number of answers you can change. Your goal is to find the maximum length of consecutive identical answers (all T's or all F's) after making at most k changes.

Example: If answerKey = "TTFTTFTT" and k = 1, you could change one 'F' to 'T' to get "TTTTTFTT", creating a sequence of 5 consecutive T's.

Input & Output

example_1.py โ€” Basic case with k=1
$ Input: answerKey = "TTFF", k = 2
โ€บ Output: 4
๐Ÿ’ก Note: We can change both F's to T's to get "TTTT", or change both T's to F's to get "FFFF". Either way gives us 4 consecutive identical answers.
example_2.py โ€” Mixed string with limited changes
$ Input: answerKey = "TFFT", k = 1
โ€บ Output: 3
๐Ÿ’ก Note: We can change the middle F to T to get "TTFT" (3 consecutive T's at start), or change a T to F to get "TFFF" (3 consecutive F's at end). Maximum is 3.
example_3.py โ€” All same characters
$ Input: answerKey = "TTTT", k = 2
โ€บ Output: 4
๐Ÿ’ก Note: The string already has 4 consecutive T's, so no changes needed. We don't need to use any of our k=2 changes.

Constraints

  • n == answerKey.length
  • 1 โ‰ค n โ‰ค 5 ร— 104
  • answerKey[i] is either 'T' or 'F'
  • 0 โ‰ค k โ‰ค n

Visualization

Tap to expand
Sliding Window for Maximum Consecutive AnswersInput: "TTFTTFTT", k = 1 (trying to maximize T's)TTFTTFTTleftrightWindow [0,4]: 4T, 1F โœ“ (F_count = 1 โ‰ค k=1)leftrightWindow [1,5]: 3T, 2F โœ— (F_count = 2 > k=1, must shrink)leftrightFinal: Window [2,7]: 5T, 1F โœ“ (Length = 6, Max so far!)Result: max(maxT=6, maxF=4) = 6
Understanding the Visualization
1
Initialize
Start with empty window, trying to maximize T's
2
Expand
Expand right pointer, count F's (characters to change)
3
Contract
When F count > k, shrink from left until valid
4
Track Maximum
Keep track of largest valid window size seen
5
Repeat for F's
Do the same process trying to maximize F's
Key Takeaway
๐ŸŽฏ Key Insight: Sliding window allows us to efficiently find the longest subarray where minority characters โ‰ค k, avoiding the need to check all possible subarrays.
Asked in
Amazon 25 Google 18 Microsoft 15 Meta 12
42.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen