Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Replace at most k characters so that the longest possible substring consists of one repeated letter; return its length.
Problem: Replace at most k characters so that the longest possible substring consists of one repeated letter; return its length.
def longest(s, k):
cnt, l, top, best = {}, 0, 0, 0
for r, c in enumerate(s):
cnt[c] = cnt.get(c, 0) + 1; top = max(top, cnt[c])
if r - l + 1 - top > k:
cnt[s[l]] -= 1; l += 1
best = max(best, r - l + 1)
return best
print(longest("ABBBACCBA", 2))What is printed?- A. 6
- B. 5
- C. 7
- D. 4
Correct answer: B. 5
The window is valid while (length − count of its most frequent letter) ≤ k. 'ABBBA' needs only its two A's changed, giving 5; every window of length 6 contains at most 3 copies of any letter, so it would need 3 changes. top is never decreased, which only delays shrinking and never inflates the answer.
More Coding Interview Problems questions
- Problem: Smallest length of a contiguous subarray of POSITIVE integers with sum ≥ target (0 if none). python def minlen(a, t): l, s, best…
- Problem: Return all start indices of anagrams of p inside s using a fixed-size window of letter counts. python from collections import…
- Problem: Intersect two lists of disjoint, sorted closed intervals. python def inter(A, B): i = j = 0; out = [] while i < len(A) and j <…
- Problem: Cars drive toward a target on a one-lane road. A car that catches a slower car ahead joins it as a fleet (moving at the slower…
- Problem: Return the minimum number of parentheses to insert to make a string valid. python def minadd(s): open, add = 0, 0 for c in s: if…
- Problem: A ramp is a pair i < j with a[i] ≤ a[j]; its width is j − i. Find the maximum width using a decreasing stack of candidate left…