Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return True if one character can be deleted from a word to make it a palindrome (or it already is one).
Problem: Return True if one character can be deleted from a word to make it a palindrome (or it already is one).
def almost(s):
def pal(i, j):
while i < j:
if s[i] != s[j]: return False
i += 1; j -= 1
return True
i, j = 0, len(s) - 1
while i < j:
if s[i] != s[j]:
return pal(i + 1, j) or pal(i, j - 1)
i += 1; j -= 1
return True
print(almost("abca"), almost("abcda"), almost("deeee"))What is printed?- A. True True True
- B. True False True
- C. False False True
- D. True False False
Correct answer: B. True False True
At the first mismatch try skipping either side once. "abca": skip 'b' or 'c' → palindrome. "abcda": after a…a, 'b' vs 'd' mismatch, and neither "cd" nor "bc" is a palindrome. "deeee": skip 'd'. O(n) – only one branch point is ever explored.
More Coding Interview Problems questions
- 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…
- Problem: Check whether s2 contains a permutation of s1 as a substring. python def hasperm(s1, s2): k = len(s1) need = [0] 26; win = [0] 26…
- Problem: Return the longest common prefix of a list of file paths. python def lcp(words): if not words: return "" p = words[0] for w in…
- Problem: Compute the minimum number of characters to add at the end of s so that it becomes a palindrome, using the KMP prefix function…