Microsoft Coding Interview: Longest Palindromic Subsequence
Question Description
Problem overview
Given a string s, compute the length of its longest palindromic subsequence (LPS). A subsequence is formed by deleting zero or more characters without reordering. You should return an integer representing the maximum length of a subsequence of s that reads the same forwards and backwards. Handle edge cases such as the empty string and short inputs.
What you'll be asked to do
You will typically clarify constraints (n = |s|, allowed characters), discuss brute-force vs. DP, and then implement a correct solution. Interviewers expect you to explain time and space complexity, and optionally provide a space-optimized version. You may be asked to reconstruct the subsequence itself or adapt the approach for related problems.
High-level approach (flow)
- Clarify input/output and examples.
- Show a recursive relation: if s[i]==s[j], LPS(i,j)=2+LPS(i+1,j-1); else max of excluding one end.
- Convert to bottom-up DP using a 2D table (or use LCS between s and reverse(s)).
- Optimize space to O(n) by using rolling arrays when possible.
- Test edge cases and analyze complexity.
Skill signals
You should demonstrate dynamic programming intuition, ability to derive recurrence relations, correctness reasoning, complexity analysis (O(n^2) time, O(n^2) or O(n) space), and familiarity with string-handling techniques (LCS reduction, two-pointer thinking, reconstruction).
Common Follow-up Questions
- •How would you reconstruct one actual longest palindromic subsequence (not just its length)? Explain additional space/time costs.
- •Can you implement a space-optimized solution that uses O(n) memory? Show why rolling arrays or reducing to LCS(s, reverse(s)) still produces the correct length.
- •Prove the equivalence between LPS(s) and LCS(s, reverse(s)). When does this reduction fail or require care?
- •How would you modify your solution to count the number of distinct palindromic subsequences (or to return them)? What changes in complexity are needed?
Related Questions
Explore More Questions
Practice This Question with AI
Get real-time hints, detailed requirements, and insightful analysis of the question.