Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA

Problem: Return the length of the longest palindromic subsequence (not substring).

Problem: Return the length of the longest palindromic subsequence (not substring).
def lps(s):
    n = len(s); dp = [[0] * n for _ in range(n)]
    for i in range(n - 1, -1, -1):
        dp[i][i] = 1
        for j in range(i + 1, n):
            dp[i][j] = dp[i+1][j-1] + 2 if s[i] == s[j] else max(dp[i+1][j], dp[i][j-1])
    return dp[0][n - 1]
print(lps("bbbab"), lps("character"), lps("abcd"))
What is printed?
  1. A. 3 5 1
  2. B. 4 3 1
  3. C. 4 5 0
  4. D. 4 5 1

Correct answer: D. 4 5 1

Interval DP: equal ends add 2 to the inside answer, otherwise drop one end. "bbbab" → "bbbb" (4). "character" → "carac" (5), although its longest palindromic substring is only "ara" (3). Any single letter is a palindrome, so "abcd" gives 1. O(n²) time and space. It also equals LCS(s, reverse(s)).

More Coding Interview Problems questions

Exams that ask this topic