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?- A. 3 5 1
- B. 4 3 1
- C. 4 5 0
- 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
- Problem: Multiply a chain of matrices with dimensions given as p (matrix i is p[i−1] × p[i]) using the fewest scalar multiplications…
- Problem: A DP solution for 'minimum coins for amount A using c denominations' with A ≤ 10⁴ and c ≤ 100 is accepted. A friend proposes…
- Problem: Find the largest square of 1s in a binary matrix and return its area. python def square(m): R, C = len(m), len(m[0]); dp = [[0]…
- Problem: Buy and sell a stock any number of times with a one-day cooldown after each sale. Maximise profit. python def cooldown(p): hold…
- Problem: Count the number of distinct ways to reach target t by putting + or − in front of every number. python from functools import…
- Problem: Generate all subsets of a set of feature flags (backtracking) and count those whose sum equals a target. python def count(a, t…