The Wayback Machine - https://web.archive.org/web/20240804234901/https://www.geeksforgeeks.org/longest-common-substring-space-optimized-dp-solution/
Open In App

Longest Common Substring (Space optimized DP solution)

Last Updated : 26 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given two strings ‘X’ and ‘Y’, find the length of longest common substring. Expected space complexity is linear.
Examples : 
 

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.

 

longest-common-substring

 

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. 
 

C++




// Space optimized CPP implementation of longest
// common substring.
#include <bits/stdc++.h>
using namespace std;
 
// Function to find longest common substring.
int LCSubStr(string X, string Y)
{
    // Find length of both the strings.
    int m = X.length();
    int n = Y.length();
 
    // Variable to store length of longest
    // common substring.
    int result = 0;
 
    // Matrix to store result of two
    // consecutive rows at a time.
    int len[2][n];
 
    // Variable to represent which row of
    // matrix is current row.
    int currRow = 0;
 
    // For a particular value of i and j,
    // len[currRow][j] stores length of longest
    // common substring in string X[0..i] and Y[0..j].
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0 || j == 0) {
                len[currRow][j] = 0;
            }
            else if (X[i - 1] == Y[j - 1]) {
                len[currRow][j] = len[1 - currRow][j - 1] + 1;
                result = max(result, len[currRow][j]);
            }
            else {
                len[currRow][j] = 0;
            }
        }
 
        // Make current row as previous row and previous
        // row as new current row.
        currRow = 1 - currRow;
    }
 
    return result;
}
 
int main()
{
    string X = "GeeksforGeeks";
    string Y = "GeeksQuiz";
 
    cout << LCSubStr(X, Y);
    return 0;
}


Java




// Space optimized CPP implementation of
// longest common substring.
import java.io.*;
import java.util.*;
 
public class GFG {
     
    // Function to find longest
    // common substring.
    static int LCSubStr(String X, String Y)
    {
         
        // Find length of both the strings.
        int m = X.length();
        int n = Y.length();
     
        // Variable to store length of longest
        // common substring.
        int result = 0;
     
        // Matrix to store result of two
        // consecutive rows at a time.
        int [][]len = new int[2][n];
     
        // Variable to represent which row of
        // matrix is current row.
        int currRow = 0;
     
        // For a particular value of
        // i and j, len[currRow][j]
        // stores length of longest
        // common substring in string
        // X[0..i] and Y[0..j].
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0) {
                    len[currRow][j] = 0;
                }
                else if (X.charAt(i - 1) ==
                              Y.charAt(j - 1))
                {
                    len[currRow][j] =
                      len[(1 - currRow)][(j - 1)]
                                             + 1;
                    result = Math.max(result,
                                len[currRow][j]);
                }
                else
                {
                    len[currRow][j] = 0;
                }
            }
     
            // Make current row as previous
            // row and previous row as
            // new current row.
            currRow = 1 - currRow;
        }
     
        return result;
    }
     
    // Driver Code
    public static void main(String args[])
    {
        String X = "GeeksforGeeks";
        String Y = "GeeksQuiz";
     
        System.out.print(LCSubStr(X, Y));
    }
}
 
// This code is contributed by
// Manish Shaw (manishshaw1)


Python3




# Space optimized Python3 implementation 
# of longest common substring.
import numpy as np
 
# Function to find longest common substring.
def LCSubStr(X, Y) :
 
    # Find length of both the strings.
    m = len(X)
    n = len(Y)
 
    # Variable to store length of
    # longest common substring.
    result = 0
 
    # Matrix to store result of two
    # consecutive rows at a time.
    len_mat = np.zeros((2, n))
 
    # Variable to represent which row 
    # of matrix is current row.
    currRow = 0
 
    # For a particular value of i and j,
    # len_mat[currRow][j] stores length of
    # longest common substring in string
    # X[0..i] and Y[0..j].
    for i in range(m) :
        for j in range(n) :
                         
            if (i == 0 | j == 0) :
                len_mat[currRow][j] = 0
             
            elif (X[i - 1] == Y[j - 1]) :
                                 
                len_mat[currRow][j] = len_mat[1 - currRow][j - 1] + 1
                result = max(result, len_mat[currRow][j])
             
            else :
                len_mat[currRow][j] = 0
             
        # Make current row as previous row and
        # previous row as new current row.
        currRow = 1 - currRow
 
    return result
 
# Driver Code
if __name__ == "__main__" :
 
    X = "GeeksforGeeks"
    Y = "GeeksQuiz"
 
    print(LCSubStr(X, Y))
 
# This code is contributed by Ryuga


C#




// Space optimized C# implementation
// of longest common substring.
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to find longest
    // common substring.
    static int LCSubStr(string X, string Y)
    {
         
        // Find length of both the strings.
        int m = X.Length;
        int n = Y.Length;
     
        // Variable to store length of longest
        // common substring.
        int result = 0;
     
        // Matrix to store result of two
        // consecutive rows at a time.
        int [,]len = new int[2,n];
     
        // Variable to represent which row of
        // matrix is current row.
        int currRow = 0;
     
        // For a particular value of
        // i and j, len[currRow][j]
        // stores length of longest
        // common substring in string
        // X[0..i] and Y[0..j].
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (i == 0 || j == 0) {
                    len[currRow,j] = 0;
                }
                else if (X[i - 1] == Y[j - 1]) {
                    len[currRow,j] = len[(1 - currRow),
                                          (j - 1)] + 1;
                    result = Math.Max(result, len[currRow, j]);
                }
                else
                {
                    len[currRow,j] = 0;
                }
            }
     
            // Make current row as previous
            // row and previous row as
            // new current row.
            currRow = 1 - currRow;
        }
     
        return result;
    }
     
     
    // Driver Code
    public static void Main()
    {
        string X = "GeeksforGeeks";
        string Y = "GeeksQuiz";
     
        Console.Write(LCSubStr(X, Y));
    }
}
 
// This code is contributed by
// Manish Shaw (manishshaw1)


PHP




<?php
// Space optimized PHP implementation
// of longest common substring.
 
// Function to find
// longest common substring.
function LCSubStr($X, $Y)
{
    // Find length of
    // both the strings.
    $m = strlen($X);
    $n = strlen($Y);
 
    // Variable to store length
    // of longest common substring.
    $result = 0;
 
    // Matrix to store result of two
    // consecutive rows at a time.
    $len = array(array(), array(), );
 
    // Variable to represent which
    // row of matrix is current row.
    $currRow = 0;
 
    // For a particular value of
    // i and j, len[currRow][j]
    // stores length of longest
    // common substring in string
    // X[0..i] and Y[0..j].
    for ($i = 0; $i <= $m; $i++)
    {
        for ($j = 0; $j <= $n; $j++)
        {
            if ($i == 0 || $j == 0)
            {
                $len[$currRow][$j] = 0;
            }
            else if ($X[$i - 1] == $Y[$j - 1])
            {
                $len[$currRow][$j] =
                        $len[1 - $currRow][$j - 1] + 1;
                 
                $result = max($result,
                              $len[$currRow][$j]);
            }
            else
            {
                $len[$currRow][$j] = 0;
            }
        }
 
        // Make current row as
        // previous row and previous
        // row as new current row.
        $currRow = 1 - $currRow;
    }
 
    return $result;
}
 
// Driver Code
$X = "GeeksforGeeks";
$Y = "GeeksQuiz";
 
print (LCSubStr($X, $Y));
 
// This code is contributed by
// Manish Shaw(manishshaw1)
?>


Javascript




<script>
 
// Space optimized CPP implementation of longest
// common substring.
 
// Function to find longest common substring.
function LCSubStr(X, Y)
{
    // Find length of both the strings.
    var m = X.length;
    var n = Y.length;
 
    // Variable to store length of longest
    // common substring.
    var result = 0;
 
    // Matrix to store result of two
    // consecutive rows at a time.
    var len = Array.from(Array(2), ()=> Array(n));
 
    // Variable to represent which row of
    // matrix is current row.
    var currRow = 0;
 
    // For a particular value of i and j,
    // len[currRow][j] stores length of longest
    // common substring in string X[0..i] and Y[0..j].
    for (var i = 0; i <= m; i++) {
        for (var j = 0; j <= n; j++) {
            if (i == 0 || j == 0) {
                len[currRow][j] = 0;
            }
            else if (X[i - 1] == Y[j - 1]) {
                len[currRow][j] = len[1 - currRow][j - 1] + 1;
                result = Math.max(result, len[currRow][j]);
            }
            else {
                len[currRow][j] = 0;
            }
        }
 
        // Make current row as previous row and previous
        // row as new current row.
        currRow = 1 - currRow;
    }
 
    return result;
}
 
// Driver code
var X = "GeeksforGeeks";
var Y = "GeeksQuiz";
document.write( LCSubStr(X, Y));
 
// This code is contributed by itsok.
</script>


Output : 

5

 

Time Complexity: O(m*n) 
Auxiliary Space: O(n)
 



Previous Article
Next Article

Similar Reads

Number of n digit stepping numbers | Space optimized solution
Given n, find the count of n digit Stepping numbers. A number is called a stepping number if all adjacent digits have an absolute difference of 1. 321 is a Stepping Number while 421 is not.Examples: Input : 2 Output : 17 The numbers are 10, 12, 21, 23, 32, 34, 43, 45, 54, 56, 65, 67, 76, 78, 87, 89, 98. Input : 1 Output : 10 The numbers are 0, 1, 2
9 min read
Word Wrap problem ( Space optimized solution )
Given a sequence of words, and a limit on the number of characters that can be put in one line (line width). Put line breaks in the given sequence such that the lines are printed neatly. Assume that the length of each word is smaller than the line width. When line breaks are inserted there is a possibility that extra spaces are present in each line
15+ min read
Printing Matrix Chain Multiplication (A Space Optimized Solution)
Prerequisite : Dynamic Programming | Set 8 (Matrix Chain Multiplication)Given a sequence of matrices, find the most efficient way to multiply these matrices together. The problem is not actually to perform the multiplications, but merely to decide in which order to perform the multiplications. We have many options to multiply a chain of matrices be
12 min read
A Space Optimized Solution of LCS
Given two strings, find the length of the longest subsequence present in both of them. Examples: 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 a typical dynamic programming-based solution for LCS. We can optimize the space used by LCS probl
14 min read
A Space Optimized DP solution for 0-1 Knapsack Problem
Given the weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack. In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent values and weights associated with n items respectively. Also given an integer W which represents knapsack capacity, find out the max
15+ min read
Print Longest Bitonic subsequence (Space Optimized Approach)
Given an array arr[] of size N, the task is to print the longest bitonic subsequence of the given array.Note: If more than one solution exit then prints anyone solution. Examples: Input: arr[] = {1, 11, 2, 10, 4, 5, 2, 1} Output: 1 11 10 5 2 1 Explanation: All possible longest bitonic subsequences from the above array are {1, 2, 10, 4, 2, 1}, {1, 1
11 min read
Design and Implement Special Stack Data Structure | Added Space Optimized Version
Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure
15+ min read
Vertical Sum in Binary Tree | Set 2 (Space Optimized)
Given a Binary Tree, find vertical sum of the nodes that are in same vertical line. Print all sums through different vertical lines. Examples: 1 / \ 2 3 / \ / \ 4 5 6 7 The tree has 5 vertical linesVertical-Line-1 has only one node 4 =&gt; vertical sum is 4 Vertical-Line-2: has only one node 2=&gt; vertical sum is 2 Vertical-Line-3: has three nodes
12 min read
Optimized Longest Path is NP Complete
Optimized Longest Path Problem: The optimized longest path problem states that given a graph G, of a set of vertices V and edges E, the task is to prove that there is a path of length at least K between a set of nodes Vs and Ve. Problem Statement: Given a graph G(V, E, K) and a set of nodes Vs and Ve with the sequence of nodes, of length ≥ K. Expla
4 min read
Find initial integral solution of Linear Diophantine equation if finite solution exists
Given three integers a, b, and c representing a linear equation of the form: ax + by = c. The task is to find the initial integral solution of the given equation if a finite solution exists. A Linear Diophantine equation (LDE) is an equation with 2 or more integer unknowns and the integer unknowns are each to at most degree of 1. Linear Diophantine
8 min read
three90RightbarBannerImg