Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the length of the longest substring that can be turned into a single repeated letter by changing at most k characters.
Problem: Find the length of the longest substring that can be turned into a single repeated letter by changing at most k characters.
def longest_rep(s, k):
cnt = [0] * 26
l = maxf = best = 0
for r, ch in enumerate(s):
cnt[ord(ch) - 65] += 1
maxf = max(maxf, cnt[ord(ch) - 65])
while r - l + 1 - maxf > k:
cnt[ord(s[l]) - 65] -= 1
l += 1
best = max(best, r - l + 1)
return best
print(longest_rep("AABABBA", 1), longest_rep("ABCDE", 2))What is printed?- A. 5 3
- B. 4 2
- C. 3 3
- D. 4 3
Correct answer: D. 4 3
A window is fixable if its length minus the count of its most frequent letter is ≤ k. "AABABBA" with k = 1 gives "AABA" or "ABBB"-style windows of length 4; "ABCDE" with k = 2 gives any 3 letters. maxf never decreases, which is safe because only a larger maxf can produce a longer answer. O(26 + n).
More Coding Interview Problems questions
- Problem: Return the smallest window of s that contains every character of t (with multiplicity). python from collections import Counter…
- Problem: A username is valid if it reads the same forwards and backwards after removing non-alphanumeric characters and ignoring case…
- Problem: Return True if one character can be deleted from a word to make it a palindrome (or it already is one). python def almost(s): def…
- Problem: Compress a string by replacing each run with the letter followed by the run length (only when the run is longer than 1). python…
- Problem: Reverse the order of words in a sentence, collapsing multiple spaces. python s = " the sky is blue " print("|" + "…
- Problem: Find the first non-repeating character in a string of lowercase letters; return its index or −1. java static int…