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)- A. 10
- B. 6
- C. 12
- 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.
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- A min-stack keeps a second stack of running minimums. What is printed? python st, mn, out = [], [], [] for op in [7, 7, "pop", 3, "pop"…
- An array of 8 zeros (indices 0–7) receives range updates with a difference array (diff[l] += v, diff[r + 1] −= v, then prefix-sum): add 5…
- Count pairs with a given difference k (k > 0) among DISTINCT values using a hash set. What is printed? python a, k = [2, 11, 6, 2, 5, 9…
- LSD radix sort (base 10, stable sort on each digit, units digit first) is applied to [134, 461, 324, 794, 742, 141, 668]. What is the list…
- What is the length of the smallest substring of "baddcacdabcbd" that contains every distinct character of the string at least once?…
- A circular queue in an array of size 7 keeps one slot empty to tell full from empty (front = rear means empty; (rear + 1) mod 7 = front…