Data Structures & AlgorithmsVery hardTCS Digital · Infosys SP

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 = "BBBBABBAAABA", 1
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. 7
  3. C. 4
  4. D. 9

Correct answer: B. 7

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

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

Exams that ask this topic