Compute longest palindromic subsequence
Company: J.P. Morgan
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Quick Answer: This question evaluates understanding of dynamic programming for strings, specifically longest palindromic subsequence concepts such as memoization, bottom-up DP, space optimization and subsequence reconstruction.
Part 1: Compute the Length of the Longest Palindromic Subsequence
Constraints
- 0 <= len(s) <= 2000
- Character comparisons are case-sensitive.
Examples
Input: "bbbab"
Expected Output: 4
Explanation: One longest palindromic subsequence is 'bbbb'.
Input: "cbbd"
Expected Output: 2
Explanation: The longest palindromic subsequence is 'bb'.
Hints
- Try defining dp[i][j] as the answer for the substring from index i to j.
- If s[i] == s[j], those two characters can wrap a smaller palindromic subsequence. Otherwise, try skipping one end.
Part 2: Reconstruct One Longest Palindromic Subsequence
Constraints
- 0 <= len(s) <= 2000
- The returned value must be both a palindrome and a subsequence of s.
- Character comparisons are case-sensitive.
Examples
Input: "bbbab"
Expected Output: "bbbb"
Explanation: The reconstruction picks matching outer b characters and then another matching pair.
Input: "cbbd"
Expected Output: "bb"
Explanation: The longest palindromic subsequence is uniquely 'bb'.
Hints
- First compute the LPS length for every substring, then walk inward from both ends to rebuild an answer.
- Build the result using a left half and a right half; when both skip choices are equally good, move the left pointer forward.