Maximize the Confusion of an Exam
Problem Statement
A teacher has written the answer key for a true/false test as a string answerKey, where each character is 'T' (true) or 'F' (false).
The teacher wants to confuse the students by making the longest possible run of identical answers in a row (all 'T' or all 'F').
The teacher may change at most k answers (turn a 'T' into an 'F' or the other way round).
Return the length of the longest run of the same answer the teacher can make.
A string answerKey made of 'T' and 'F', and an integer k.
One integer: the longest block of identical answers possible after at most k changes.
Change both F's to T (or both T's to F). The whole key is one letter.
Change the first T to F to get "FFFT", or the last T to get "TFFF". Either way the run has length 3.
Change the first F to get "TTTTTFTT" (run of 5), or the second F to get "TTFTTTTT" (also 5).
- • 1 ≤ answerKey.length ≤ 5 · 10^4
- • answerKey[i] is 'T' or 'F'
- • 1 ≤ k ≤ answerKey.length
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each start, grow right while min(T count, F count) ≤ k
Longest window with ≤ k F's, longest window with ≤ k T's, take the max
Try every start. Grow the end while counting T's and F's. To make the block all one letter, change the smaller group, which costs min(countT, countF). While that is ≤ k, the block is a candidate. When it goes above k, stop for this start.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.