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 = "AAAABABBAABA", 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. 10
  2. B. 6
  3. C. 12
  4. D. 7

Correct answer: D. 7

A window is fixable if (length − count of its most frequent letter) ≤ k = 2; the widest such window is 'AAAABAB' of length 7. Using k = 1 gives 6, k = 3 gives 10, and 12 is the whole string.

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

Exams that ask this topic