Java String Program · S43
Longest Palindromic Subsequence in Java
A subsequence keeps characters in order but may skip some. Find the longest one that reads the same in both directions, using a table of answers for every substring.
Problem Statement
Given a string, return the length of its longest subsequence that is a palindrome. A subsequence is formed by deleting zero or more characters without changing the order of the rest.
Unlike a substring, the characters do not have to be next to each other. An empty string has length 0.
Input/Output Examples
"character"Output5Explanation: "carac" is a palindromic subsequence: c, a, r, a, c."abca"Output3Explanation: "aba" or "aca" both have length 3."abcd"Output1Explanation: any single character is a palindrome.Visual Explanation
| i \ j | a | b | c | a |
|---|---|---|---|---|
| a | 1 | 1 | 1 | 3 |
| b | 1 | 1 | 1 | |
| c | 1 | 1 | ||
| a | 1 |
"abca": dp[i][j] is the answer for the substring from i to j. The ends of the whole string match, so the answer (purple) is the inner value (amber) plus 2.Every cell depends only on shorter substrings: the cell below-left when the ends match, or the cell below or to the left when they do not. Filling the table from short substrings to long ones guarantees those values are ready.
Approaches
Both approaches fill an n × n table. The first works on substrings directly; the second reuses the longest common subsequence algorithm.
Approach 1: Interval DP (Recommended)
Idea: dp[i][j] is the answer for s[i..j]: if the ends match, add 2 to the inner answer; otherwise take the better of dropping either end.
- Set
dp[i][i] = 1for every single character. - Process
ifrom the end of the string to the start, andjfromi + 1to the end. - If
s[i] == s[j],dp[i][j] = dp[i + 1][j - 1] + 2. - Otherwise,
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]).
Time: O(n²) · Space: O(n²).
Approach 2: LCS With the Reverse
Idea: a palindromic subsequence appears in the same order in s and in reverse(s), so the answer is their longest common subsequence.
- Reverse the string.
- Run the LCS recurrence on
sand its reverse. - Keep only the previous row to save memory.
Time: O(n²) · Space: O(n).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Interval DP (Recommended)
Iterating i backwards makes sure dp[i + 1][…] is filled before it is needed.
public class PalSubseqInterval {
// dp[i][j] = length of the longest palindromic subsequence of s[i..j]
static int longestPalindromicSubsequence(String s) {
int n = s.length();
if (n == 0) {
return 0;
}
int[][] dp = new int[n][n];
for (int i = n - 1; i >= 0; i--) {
dp[i][i] = 1;
for (int j = i + 1; j < n; j++) {
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1] + 2; // both ends join the palindrome
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
public static void main(String[] args) {
String[] inputs = {"character", "abca", "abcd"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + longestPalindromicSubsequence(s));
}
}
}
"character" -> 5 "abca" -> 3 "abcd" -> 1
Time complexity: O(n²) · Space complexity: O(n²).
Approach 2: LCS With the Reverse
Reduces the problem to a classic one, and the rolling row cuts memory to two arrays of length n + 1.
public class PalSubseqLcs {
// A palindromic subsequence reads the same in s and in reverse(s): it is their LCS
static int longestPalindromicSubsequence(String s) {
String r = new StringBuilder(s).reverse().toString();
int n = s.length();
int[] prev = new int[n + 1];
for (int i = 1; i <= n; i++) {
int[] cur = new int[n + 1];
for (int j = 1; j <= n; j++) {
cur[j] = s.charAt(i - 1) == r.charAt(j - 1)
? prev[j - 1] + 1
: Math.max(prev[j], cur[j - 1]);
}
prev = cur;
}
return prev[n];
}
public static void main(String[] args) {
String[] inputs = {"character", "abca", "abcd"};
for (String s : inputs) {
System.out.println("\"" + s + "\" -> " + longestPalindromicSubsequence(s));
}
}
}
"character" -> 5 "abca" -> 3 "abcd" -> 1
Time complexity: O(n²) · Space complexity: O(n).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Interval DP | O(n²) | O(n²) |
| LCS With the Reverse | O(n²) | O(n) |
Here n is the length of the string. Both approaches compute n² table entries in constant time each; the LCS version stores only one row at a time.
Interview Tips and Recommended Approach
- Distinguish subsequence from substring. The longest palindromic substring is a different problem with different solutions.
- Explain the fill order. Each cell needs shorter intervals, so iterate
idownwards. - Know the deletion connection. The fewest deletions to make a string a palindrome is
nminus this answer. - Mention the memory optimisation when the interviewer asks about long strings.
Recommended Approach: Interval DP
Why: it states the recurrence directly in terms of the string's ends, which is easy to explain and to extend, for example to reconstruct the subsequence itself.