Boundary update without `+1` / `-1`
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Move from brute-force thinking to an efficient approach using binary search strategy.
A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row).
You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation:
'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F').Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.
Example 1:
Input: answerKey = "TTFF", k = 2 Output: 4 Explanation: We can replace both the 'F's with 'T's to make answerKey = "TTTT". There are four consecutive 'T's.
Example 2:
Input: answerKey = "TFFT", k = 1 Output: 3 Explanation: We can replace the first 'T' with an 'F' to make answerKey = "FFFT". Alternatively, we can replace the second 'T' with an 'F' to make answerKey = "TFFF". In both cases, there are three consecutive 'F's.
Example 3:
Input: answerKey = "TTFTTFTT", k = 1 Output: 5 Explanation: We can replace the first 'F' to make answerKey = "TTTTTFTT" Alternatively, we can replace the second 'F' to make answerKey = "TTFTTTTT". In both cases, there are five consecutive 'T's.
Constraints:
n == answerKey.length1 <= n <= 5 * 104answerKey[i] is either 'T' or 'F'1 <= k <= nProblem summary: A teacher is writing a test with n true/false questions, with 'T' denoting true and 'F' denoting false. He wants to confuse the students by maximizing the number of consecutive questions with the same answer (multiple trues or multiple falses in a row). You are given a string answerKey, where answerKey[i] is the original answer to the ith question. In addition, you are given an integer k, the maximum number of times you may perform the following operation: Change the answer key for any question to 'T' or 'F' (i.e., set answerKey[i] to 'T' or 'F'). Return the maximum number of consecutive 'T's or 'F's in the answer key after performing the operation at most k times.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Binary Search · Sliding Window
"TTFF" 2
"TFFT" 1
"TTFTTFTT" 1
longest-substring-with-at-most-k-distinct-characters)longest-repeating-character-replacement)max-consecutive-ones-iii)minimum-number-of-days-to-make-m-bouquets)longest-nice-subarray)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2024: Maximize the Confusion of an Exam
class Solution {
private char[] s;
private int k;
public int maxConsecutiveAnswers(String answerKey, int k) {
s = answerKey.toCharArray();
this.k = k;
return Math.max(f('T'), f('F'));
}
private int f(char c) {
int l = 0, cnt = 0;
for (char ch : s) {
cnt += ch == c ? 1 : 0;
if (cnt > k) {
cnt -= s[l++] == c ? 1 : 0;
}
}
return s.length - l;
}
}
// Accepted solution for LeetCode #2024: Maximize the Confusion of an Exam
func maxConsecutiveAnswers(answerKey string, k int) int {
f := func(c byte) int {
l, cnt := 0, 0
for _, ch := range answerKey {
if byte(ch) == c {
cnt++
}
if cnt > k {
if answerKey[l] == c {
cnt--
}
l++
}
}
return len(answerKey) - l
}
return max(f('T'), f('F'))
}
# Accepted solution for LeetCode #2024: Maximize the Confusion of an Exam
class Solution:
def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
def f(c: str) -> int:
cnt = l = 0
for ch in answerKey:
cnt += ch == c
if cnt > k:
cnt -= answerKey[l] == c
l += 1
return len(answerKey) - l
return max(f("T"), f("F"))
// Accepted solution for LeetCode #2024: Maximize the Confusion of an Exam
impl Solution {
pub fn max_consecutive_answers(answer_key: String, k: i32) -> i32 {
let n = answer_key.len();
let k = k as usize;
let s: Vec<char> = answer_key.chars().collect();
let f = |c: char| -> usize {
let mut l = 0;
let mut cnt = 0;
for &ch in &s {
cnt += if ch == c { 1 } else { 0 };
if cnt > k {
cnt -= if s[l] == c { 1 } else { 0 };
l += 1;
}
}
n - l
};
std::cmp::max(f('T'), f('F')) as i32
}
}
// Accepted solution for LeetCode #2024: Maximize the Confusion of an Exam
function maxConsecutiveAnswers(answerKey: string, k: number): number {
const n = answerKey.length;
const f = (c: string): number => {
let [l, cnt] = [0, 0];
for (const ch of answerKey) {
cnt += ch === c ? 1 : 0;
if (cnt > k) {
cnt -= answerKey[l++] === c ? 1 : 0;
}
}
return n - l;
};
return Math.max(f('T'), f('F'));
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: Using `if` instead of `while` leaves the window invalid for multiple iterations.
Usually fails on: Over-limit windows stay invalid and produce wrong lengths/counts.
Fix: Shrink in a `while` loop until the invariant is valid again.