Given two strings, find the length of longest subsequence present in both of them.
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
We have discussed typical dynamic programming based solution for LCS. We can optimize space used by lcs problem. We know recurrence relation of LCS problem is
How to find length of LCS in O(n) auxiliary space?
One important observation in above simple implementation is, in each iteration of outer loop we only, need values from all columns of previous row. So there is no need of storing all rows in our DP matrix, we can just store two rows at a time and use them, in that way used space will reduce from L[m+1][n+1] to L[n+1]. Below is the implementation of above idea.
Length of LCS is 4
Time Complexity : O(m*n)
Auxiliary Space : O(n)
This article is contributed Shivam Mittal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- A Space Optimized DP solution for 0-1 Knapsack Problem
- Word Wrap problem ( Space optimized solution )
- Longest Common Substring (Space optimized DP solution)
- Printing Matrix Chain Multiplication (A Space Optimized Solution)
- Vertical Sum in Binary Tree | Set 2 (Space Optimized)
- Design and Implement Special Stack Data Structure | Added Space Optimized Version
- Optimized Naive Algorithm for Pattern Searching
- Optimized Euler Totient Function for Multiple Evaluations
- Dial's Algorithm (Optimized Dijkstra for small range weights)
- Josephus problem | Set 1 (A O(n) Solution)
- Find four elements that sum to a given value | Set 1 (n^3 solution)
- Josephus problem | Set 2 (A Simple Solution when k = 2)
- Josephus Problem | (Iterative Solution)
- Find four elements that sum to a given value | Set 2 ( O(n^2Logn) Solution)
- Find Cube Pairs | Set 2 (A n^(1/3) Solution)
Improved By : shiv_bhakt