Longest Palindromic Subsequence in Python Last Updated : 22 May, 2024 Comments Improve Suggest changes Like Article Like Report Longest Palindromic Subsequence (LPS) problem is about finding the longest subsequence of the given sequence which is a palindrome. In Python, the task of maximizing the number of words in a sentence can be solved by the methods of dynamic programming. The algorithm for finding the Longest Palindromic Subsequence involves creating a table to store the lengths of the longest palindromic subsequences for different substrings of the input sequence. Longest Palindromic Subsequence in Python using Memoization:Step-by-step algorithm: Define a recursive function, say lps(s1, s2, n1, n2) which finds the longest common subsequence among s1 and s2 where n1 is index of s1 and n2 is index of s2.Call the lps function with input string seq as s1 and reverse of seq as s2.If we reach the first index of any string, return 0Check if we have already computed the result for the current indices.If the result is already computed, return the result.Otherwise, if the current indices of both s1 and s2 are equal, dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1)Else if the current index of both s1 and s2 are not equal, dp[n1][n2] = max(lps(s1, s2, n1 - 1, n2), lps(s1, s2, n1, n2 - 1))Store the above result in dp[n1][n2]Below is the implementation of Longest Palindromic Subsequence in Python using Memoization: Python # A Dynamic Programming based Python program for LPS problem # Returns the length of the longest palindromic subsequence # in seq dp = [[-1 for i in range(1001)]for j in range(1001)] # Returns the length of the longest palindromic subsequence # in seq def lps(s1, s2, n1, n2): if (n1 == 0 or n2 == 0): return 0 if (dp[n1][n2] != -1): return dp[n1][n2] if (s1[n1 - 1] == s2[n2 - 1]): dp[n1][n2] = 1 + lps(s1, s2, n1 - 1, n2 - 1) return dp[n1][n2] else: dp[n1][n2] = max(lps(s1, s2, n1 - 1, n2), lps(s1, s2, n1, n2 - 1)) return dp[n1][n2] # Driver program to test above functions seq = "GEEKSFORGEEKS" n = len(seq) s2 = seq s2 = s2[::-1] print(f"The length of the LPS is {lps(s2, seq, n, n)}") OutputThe length of the LPS is 5 Time Complexity: O(n2), where n is the length of the input stringAuxiliary Space: O(n2) Longest Palindromic Subsequence in Python using Tabulation:Step-by-step algorithm: Initialize a 2D array dp with dimensions (n x n), where n is the length of the input sequence.Set the diagonal elements of dp to 1, as each single character is a palindrome of length 1.Traverse the input sequence with two pointers i and j, where i starts from n-1 and decrements, and j starts from i+1 and increments.If seq[i] is equal to seq[j], set dp[i][j] to dp[i+1][j-1] + 2 because the current characters form a palindromic subsequence of length 2 greater than the one inside them.Otherwise, set dp[i][j] to the maximum of dp[i+1][j] and dp[i][j-1], as we discard one character from either end and try to find the longest palindromic subsequence.The result is stored in dp[0][n-1], which represents the length of the Longest Palindromic Subsequence.Below is the implementation of Longest Palindromic Subsequence in Python using Tabulation: Python def longestPalinSubseq(S): R = S[::-1] # dp[i][j] will store the length of the longest # palindromic subsequence for the substring # starting at index i and ending at index j dp = [[0] * (len(R) + 1) for _ in range(len(S) + 1)] # Filling up DP table based on conditions discussed # in the above approach for i in range(1, len(S) + 1): for j in range(1, len(R) + 1): if S[i - 1] == R[j - 1]: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]) # At the end, DP table will contain the LPS # So just return the length of LPS return dp[len(S)][len(R)] # Driver code s = "GEEKSFORGEEKS" print("The length of the LPS is", longestPalinSubseq(s)) OutputThe length of the LPS is 5 Time Complexity: O(n2), where n is the length of the input stringAuxiliary Space: O(n2) Comment More infoAdvertise with us Next Article Longest Palindromic Subsequence in Python A amit7822i5n Follow Improve Article Tags : Strings Dynamic Programming DSA Python-DSA Practice Tags : Dynamic ProgrammingStrings Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co 11 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example 12 min read Like