Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
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.
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.
def prefix(s):
pi = [0] * len(s)
for i in range(1, len(s)):
k = pi[i - 1]
while k and s[i] != s[k]:
k = pi[k - 1]
if s[i] == s[k]:
k += 1
pi[i] = k
return pi
s = "abcbab"
t = s[::-1] + "#" + s
print(prefix("aabaaab")[-1], len(s) - prefix(t)[-1])What is printed?- A. 2 3
- B. 3 2
- C. 2 4
- D. 3 3
Correct answer: D. 3 3
pi of "aabaaab": [0,1,0,1,2,2,3] – the last value 3 is the longest proper prefix that is also a suffix ("aab"). For s = "abcbab", the prefix function of reverse(s) + '#' + s gives the longest palindromic suffix of s ("bab", length 3), so 6 − 3 = 3 characters must be appended. Prefix function is O(n).
More Coding Interview Problems questions
- Problem: Search a pattern of length m in a text of length n = 10⁶ (m up to 10⁵) and report all match positions. Which method guarantees…
- Problem: Return the longest palindromic substring of s (first one if there is a tie). python def lps(s): best = "" for c in range(len(s))…
- Problem: Check whether a string of brackets ()[]{} is balanced. python def balanced(s): pair = {')': '(', ']': '[', '}': '{'} st = [] for…
- Problem: For each day's temperature, find how many days you must wait for a warmer day (0 if never). python def wait(t): res, st = [0]…
- Problem: Find the largest rectangle that fits under a histogram of bar heights. python def largest(h): st, best = [], 0 for i, x in…
- Problem: Evaluate an expression in Reverse Polish notation; division truncates toward zero. python def rpn(tokens): st = [] for t in…