Write a space-optimized version of the LCS problem.

We have already discussed an iterative DP version of the LCS problem that uses O(m.n) space where m and n are the length of given strings X and Y, respectively. If only the length of the LCS is required, the space complexity of the solution can be improved up to O(min(m, n)) since we are only reading from the previous row of the current row.

Practice this problem

Approach 1: (Using two arrays)

The space-optimized algorithm can be implemented as follows in C++, Java, and Python, using two arrays:

C++


Download  Run Code

Output:

The length of the LCS is 4

Java


Download  Run Code

Output:

The length of the LCS is 4

Python


Download  Run Code

Output:

The length of the LCS is 4

The time complexity of the above solution is O(m.n), where m and n are the length of given strings X and Y, respectively. The auxiliary space required by the program is O(n), which is independent of the length of the first string m. However, if the second string’s length is much larger than the first string’s length, then the space complexity would be huge. We can optimize the space complexity to O(min(m, n)) by creating a wrapper that always passes a smaller string as a second argument to the LCSLength function.

 
The program’s auxiliary space now is 2 x min(m, n).

Approach 2: (Using one array)

The above solution uses two arrays. We can further optimize the code to use only a single array and a temporary variable. The implementation can be seen below in C++, Java, and Python:

C++


Download  Run Code

Output:

The length of the LCS is 4

Java


Download  Run Code

Output:

The length of the LCS is 4

Python


Download  Run Code

Output:

The length of the LCS is 4