A Space Optimized Solution of LCS in C Program?

CProgrammingServer Side Programming

Here we will see one space optimized approach for LCS problem. The LCS is the longest common subsequence. If two strings are “BHHUBC” and “HYUYBZC”, then the length of the subsequence is 4. One dynamic programming approach is already their, but using the dynamic programming approach, it will take more space. We need table of order m x n, where m is the number of characters in first string, and n is the number of characters in the second string.

Here we will see how to implement this algorithm using O(n) amount of auxiliary space. If we observe the old approach we can see in each iteration, we need data from the previous row. Not all data are required. So if we make a table of size 2n, then it will be alright. Let us see the algorithm to get the idea.


lcs_problem(X, Y) −

   m := length of X
   n := length of Y
   define table of size L[2, n+1]
   index is to point 0th or 1st row of the table L.
   for i in range 1 to m, do
      index := index AND 1
      for j in range 0 to n, do
         if i = 0 or j = 0, then
            L[index, j] := 0
         else if X[i - 1] = Y[j - 1], then
            L[index, j] := L[1 – index, j - 1] + 1
            L[index, j] := max of L[1 – index, j] and L[index, j-1]
         end if
   return L[index, n]


#include <iostream>
using namespace std;
int lcsOptimized(string &X, string &Y) {
   int m = X.length(), n = Y.length();
   int L[2][n + 1];
   bool index;
   for (int i = 0; i <= m; i++) {
      index = i & 1;
      for (int j = 0; j <= n; j++) {
         if (i == 0 || j == 0)
            L[index][j] = 0;
         else if (X[i-1] == Y[j-1])
            L[index][j] = L[1 - index][j - 1] + 1;
            L[index][j] = max(L[1 - index][j], L[index][j - 1]);
   return L[index][n];
int main() {
   string X = "BHHUBC";
   string Y = "HYUYBZC";
   cout << "Length of LCS is :" << lcsOptimized(X, Y);


Length of LCS is :4
Published on 19-Aug-2019 17:58:42