Data Structures & AlgorithmsVery hardGATE CS · DSA

Longest substring that can be turned into one repeated letter with at most k replacements (sliding window, window − maxfreq ≤ k). What is printed?

Longest substring that can be turned into one repeated letter with at most k replacements (sliding window, window − maxfreq ≤ k). What is printed?
from collections import Counter
s, k = "ABABBABBABBB", 2
cnt, l, best, mf = Counter(), 0, 0, 0
for r, ch in enumerate(s):
    cnt[ch] += 1; mf = max(mf, cnt[ch])
    while r - l + 1 - mf > k:
        cnt[s[l]] -= 1; l += 1
    best = max(best, r - l + 1)
print(best)
  1. A. 8
  2. B. 9
  3. C. 6
  4. D. 11

Correct answer: B. 9

A window is fixable if (length − count of its most frequent letter) ≤ k. The widest such window has length 9.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic