coding
Microsoft
Google
Amazon

Microsoft Coding Interview: Longest Palindromic Subsequence

Topics:
Dynamic Programming
Strings
Two Pointers
Roles:
Software Engineer
Backend Engineer
SWE
Experience:
Entry Level
Mid Level
Senior

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)

  1. Clarify input/output and examples.
  2. Show a recursive relation: if s[i]==s[j], LPS(i,j)=2+LPS(i+1,j-1); else max of excluding one end.
  3. Convert to bottom-up DP using a 2D table (or use LCS between s and reverse(s)).
  4. Optimize space to O(n) by using rolling arrays when possible.
  5. 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

1Longest Palindromic Substring — how to solve with expand-around-center and Manacher's algorithm
2Longest Common Subsequence (LCS) — connection to palindromic subsequence problems
3Minimum deletions to make a string a palindrome — use LPS to derive the answer
4Count distinct palindromic subsequences — DP with inclusion/exclusion and indexing

Explore More Questions

Practice This Question with AI

Get real-time hints, detailed requirements, and insightful analysis of the question.

Longest Palindromic Subsequence - Microsoft Coding | Voker