Maximize the Confusion of an Exam — LeetCode 2024 Python Solution

MediumStringBinary SearchPrefix SumSliding Window
Problem
#2024
Reading time
2 min

The problem

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).

Example

Input
answerKey = "TTFF", k = 2
Output
4
Explanation
We can replace both the 'F's with 'T's to make answerKey = "TTTT".

Python solution

Python
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"))

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Sliding Window

Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2024. Maximize the Confusion of an Exam is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.

The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2024. Maximize the Confusion of an Exam?
LeetCode 2024. Maximize the Confusion of an Exam is rated Medium on LeetCode.
What topics does LeetCode 2024. Maximize the Confusion of an Exam cover?
LeetCode 2024. Maximize the Confusion of an Exam is tagged String, Binary Search, Prefix Sum and Sliding Window on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview