Skip to main content
Back to problems
#516
Medium Algorithms

Longest palindromic subsequence

String Dynamic Programming
65.1% acceptance
Feb 19, 2026
10325
345
Given a string s, find the longest palindromic subsequence's length in s. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn longest_palindrome_subseq(s: String) -> i32 {
    let s: Vec<u8> = s.bytes().collect();
    let n = s.len();
    let mut dp = vec![vec![0i32; n]; n];
    for i in 0..n { dp[i][i] = 1; }
    for len in 2..=n {
      for i in 0..=(n - len) {
        let j = i + len - 1;
        if s[i] == s[j] {
          dp[i][j] = 2 + if len == 2 { 0 } else { dp[i+1][j-1] };
        } else {
          dp[i][j] = dp[i+1][j].max(dp[i][j-1]);
        }
      }
    }
    dp[0][n - 1]
  }
}