← Home

516. Longest Palindromic Subsequence

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
dynamic programmingC++Markdown
516

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 516. Longest Palindromic Subsequence, the solution in this repository is mainly a dynamic programming solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: dynamic programming, two pointers.

The notes already sitting in the source point us in the right direction:

  • DP
  • https://github.com/keineahnung2345/leetcode-cpp-practices/blob/master/5.%20Longest%20Palindromic%20Substring.cpp

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are longestPalindromeSubseq.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//DP
02//https://github.com/keineahnung2345/leetcode-cpp-practices/blob/master/5.%20Longest%20Palindromic%20Substring.cpp
03//Runtime: 264 ms, faster than 5.98% of C++ online submissions for Longest Palindromic Subsequence.
04//Memory Usage: 67.2 MB, less than 100.00% of C++ online submissions for Longest Palindromic Subsequence.
05class Solution {
06public:
07    int longestPalindromeSubseq(string s) {
08        int n = s.size();
09        vector<vector<int>> dp(n, vector(n, 0));
10        
11        for(int i = n-1; i >= 0; i--){
12            for(int j = i; j < n; j++){
13                if(i == j){
14                    dp[i][j] = 1;
15                }else if(i+1 == j){
16                    dp[i][j] = (s[i] == s[j]) ? 2 : 1;
17                }else if(i+1 < j){
18                    dp[i][j] = max({dp[i+1][j-1] + ((s[i] == s[j]) ? 2 : 0),
19                                   dp[i+1][j],
20                                   dp[i][j-1]});
21                }
22                
23                // cout << "(" << i << ", " << j << "): " << dp[i][j] << endl;
24            }
25        }
26        
27        // cout << "==============" << endl;
28        
29        return dp[0][n-1];
30    }
31};
32
33//DP, add shortcut, O(1) space
34//Runtime: 80 ms, faster than 81.12% of C++ online submissions for Longest Palindromic Subsequence.
35//Memory Usage: 6.4 MB, less than 100.00% of C++ online submissions for Longest Palindromic Subsequence.
36//from leetcode 100% solution
37class Solution {
38public:
39    int longestPalindromeSubseq(string s) {
40        int n = s.size();
41        
42        if(n == 1) return 1;
43        if(n == 2) return (s[0] == s[1]) ? 2 : 1;
44        
45        int l = 0, r = n-1;
46        while(l <= r && s[l] == s[r]){
47            l++; r--;
48        }
49        if(l > r) return n;
50        
51        vector<int> dp(n, 0);
52        int dp_ip1_js1, dp_ip1_j;
53            
54        for(int i = n-1; i >= 0; i--){
55            /*
56            dp_ip1_js1: dp[i+1][j-1],
57            it is only used when i+1 < j,
58            i.e. there will be at least one char 
59            between s[i] and s[j], 
60            so dp[i+1][j-1] is at least 1
61            */
62            dp_ip1_js1 = 1; //reset here!!(reset for each row)
63            
64            for(int j = i; j < n; j++){
65                if(i == j){
66                    dp[j] = 1;
67                }else if(i+1 == j){
68                    dp[j] = (s[i] == s[j]) ? 2 : 1;
69                }else if(i+1 < j){
70                    dp_ip1_j = dp[j]; //dp[i+1][j]
71                    dp[j] = max({dp_ip1_js1 + ((s[i] == s[j]) ? 2 : 0),
72                                   dp[j], //dp[i+1][j]
73                                   dp[j-1] //dp[i][j-1]
74                                 });
75                    dp_ip1_js1 = dp_ip1_j;
76                }
77                
78                // cout << "(" << i << ", " << j << "): " << dp[j] << endl;
79            }
80        }
81        
82        // cout << "==============" << endl;
83        
84        return dp[n-1];
85    }
86};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.