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)
- Number of n digit stepping numbers | Space optimized solution
- Matrix Chain Multiplication (A O(N^2) Solution)
- Minimum number of jumps to reach end | Set 2 (O(n) solution)
- Compute nCr % p | Set 1 (Introduction and Dynamic Programming Solution)
- Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree)
- Subset Sum Problem in O(sum) space
- Longest palindrome subsequence with O(n) space
- Space and time efficient Binomial Coefficient
- Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
- Sorted subsequence of size 3 in linear time using constant space
- Dynamic Programming | Wildcard Pattern Matching | Linear Time and Constant Space