Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Return the longest palindromic substring of s (first one if there is a tie).
Problem: Return the longest palindromic substring of s (first one if there is a tie).
def lps(s):
best = ""
for c in range(len(s)):
for l, r in ((c, c), (c, c + 1)):
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1; r += 1
if r - l - 1 > len(best):
best = s[l + 1:r]
return best
print(lps("forgeeksskeegfor"), lps("abacdfgdcaba"))What is printed?- A. eeksskee aba
- B. geeksskeeg aba
- C. geeksskeeg abacdfgdcaba
- D. geeksskeeg cdfgdc
Correct answer: B. geeksskeeg aba
Expand around every centre (odd and even). The even centre between the two s's expands to "geeksskeeg" (length 10). In "abacdfgdcaba", "cdfgdc" is not a palindrome (f ≠ g); the longest is "aba". Taking the longest common substring of s and reverse(s) wrongly suggests "abacd"-style or "cdfgdc"-style answers unless positions are checked. O(n²) time, O(1) space.
More Coding Interview Problems questions
- 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…
- Problem: Simulate asteroids on a line: positive moves right, negative left; on collision the smaller explodes, equal sizes both explode…
- Problem: Remove k digits from a number string to make the smallest possible number (no leading zeros in the result, "0" if empty). python…