Longest Palindromic Subsequence dp solution
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
A palindrome is a sequence that reads the same backward as forward. In computational terms, the Longest Palindromic Subsequence (LPS) problem involves finding the longest subsequence within a string that is a palindrome. Unlike substrings, subsequences are not required to have consecutive characters. The LPS problem is a classic question in dynamic programming (DP), offering a beautiful display of optimal substructure and overlapping subproblems characteristics.
Dynamic Programming Approach
The dynamic programming approach to solving the LPS problem involves constructing a table to store results of subproblems, which helps avoid redundant computations.
Problem Formulation
Given a string of length $n$``, define L[i][j] as the length of the longest palindromic subsequence in the substring ``$s[i...j]$. The goal is to compute L[0][n-1].
Transition Formula
To fill the DP table, use the following rules:
- Base Case: When dealing with a single character, i.e.,
i == j, a single character is itself a palindrome of length 1. Thus: - Recurrence Relation: For longer sequences, if the boundary characters match (i.e.,
s[i] == s[j]), then they contribute to the LPS, and you can extend the solution for the inner substring:If the boundary characters do not match:
Algorithm
- Initialize a DP table
Lof size . - Set all diagonal elements
L[i][i]to 1, representing base cases of single-character palindromes. - For each substring length
clfrom 2 ton, compute LPS values using the transition formulas. - Populate
Literatively, withL[0][n-1]eventually containing the length of the LPS for the entire string.
- Time Complexity: The solution consists of a double loop, resulting in a time complexity of .
- Space Complexity: Requires an table to store intermediate results, so the space complexity is also .
- Space Optimization: The full table is often not required simultaneously. Space can be reduced to by maintaining only two rows of the DP table at any time.
- Reconstructing the LPS: For more insight, reconstruct the palindrome itself by backtracking through the table based on chosen paths.

