Given two strings ‘X’ and ‘Y’, find the length of longest common substring. Expected space complexity is linear.
Input : X = "GeeksforGeeks", Y = "GeeksQuiz" Output : 5 The longest common substring is "Geeks" and is of length 5. Input : X = "abcdxyz", Y = "xyzabcd" Output : 4 The longest common substring is "abcd" and is of length 4.
We have discussed Dynamic programming based solution for Longest common substring. The auxiliary space used by the solution is O(m*n), where m and n are lengths of string X and Y. The space used by solution can be reduced to O(2*n).
Suppose we are at position mat[i][j]. Now if X[i-1] == Y[j-1], then we add the value of mat[i-1][j-1] to our result. That is we add value from previous row and value for all other rows below the previous row are never used. So, at a time we are using only two consecutive rows. This observation can be used to reduce the space required to find length of longest common substring.
Instead of creating a matrix of size m*n, we create a matrix of size 2*n. A variable currRow is used to represent that either row 0 or row 1 of this matrix is currently used to find length. Initially row 0 is used as current row for the case when length of string X is zero. At the end of each iteration, current row is made previous row and previous row is made new current row.
Time Complexity: O(m*n)
Auxiliary Space: O(n)
- A Space Optimized Solution of LCS
- A Space Optimized DP solution for 0-1 Knapsack Problem
- Word Wrap problem ( Space optimized solution )
- Printing Matrix Chain Multiplication (A Space Optimized Solution)
- Longest Common Substring | DP-29
- Print the longest common substring
- Longest Common Substring in an Array of Strings
- SequenceMatcher in Python for Longest Common Substring
- Longest common substring in binary representation of two numbers
- Check if two strings have a common substring
- Longest Palindromic Substring | Set 2
- Longest Palindromic Substring | Set 1
- Longest substring with count of 1s more than 0s
- Longest Non-palindromic substring
- Longest substring of vowels
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.