Data Structures & AlgorithmsHardProduct Company SDE · sliding window OA

Problem: Find the length of the longest substring of 'AABABBA' that can be made all one letter after at most k = 1 replacement. Run the sliding-window code.

Problem: Find the length of the longest substring of 'AABABBA' that can be made all one letter after at most k = 1 replacement. Run the sliding-window code.
s = 'AABABBA'
k = 1
cnt = {}
l = best = mx = 0
for r, ch in enumerate(s):
    cnt[ch] = cnt.get(ch, 0) + 1
    mx = max(mx, cnt[ch])
    while (r - l + 1) - mx > k:
        cnt[s[l]] -= 1
        l += 1
    best = max(best, r - l + 1)
print(best)
What is printed?
  1. A. 4
  2. B. 3
  3. C. 5
  4. D. 6

Correct answer: A. 4

The window 'AABA' (or 'ABBA' type windows) with one replacement becomes uniform, and no window of length 5 works. The window keeps the largest same-letter count, which is the key quantity.

More Coding Interview Problems questions

Exams that ask this topic