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?
  1. A. eeksskee aba
  2. B. geeksskeeg aba
  3. C. geeksskeeg abacdfgdcaba
  4. 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

Exams that ask this topic