AlgoMaster Logo

Longest Palindromic Subsequence

Ashish

Ashish Pratap Singh

medium

Solve it on LeetCode

Approaches

1. Recursive Approach

Intuition:

The naive recursive solution involves exploring all possible subsequences of the string to determine the longest palindromic subsequence. The basic idea is to use two pointers, one starting from the beginning of the string and one from the end. If the characters at these positions match, then include them in the palindrome and move both pointers inward. If they don't match, recursively solve for both possibilities by moving either pointer inward to find the longest subsequence.

Code:

2. Memoization Approach

Intuition:

To improve upon the recursive approach and avoid recalculating results for the same subproblems, memoization can be used. This involves caching results of previously computed states defined by their start and end indices.

Code:

3. Dynamic Programming Approach

Intuition:

The most efficient way uses a bottom-up dynamic programming approach. We define a table dp where dp[i][j] represents the length of the longest palindromic subsequence between indices i and j. If the characters match, extend the subsequence by two; otherwise, choose the longest subsequence between [i+1, j] and [i, j-1].

Code: