Statement
Solution
Naive approach
A naive approach would be to compare the characters of both strings based on the following rules:
-
If the current characters of both strings match, we move one position ahead in both strings.
-
If the current characters of both strings do not match, we recursively calculate the maximum length of moving one character forward in any one of the two strings i.e., we check if moving a character forward in either the first string or the second will give us a longer subsequence.
-
If we reach the end of either of the two strings, we return .
The time complexity of the naive approach is , where and are the lengths of the two strings, respectively. The space complexity of this approach is .
Optimized approach using dynamic programming
We are going to solve this problem with the help of the top-down approach of dynamic programming. The top-down solution, commonly known as the memoization technique, is an enhancement of the recursive solution. It overcomes the problem of calculating redundant solutions over and over again by storing them in an array. In the recursive approach, the following two variables kept changing:
-
The index,
i
, used to keep track of the current character instr1
. -
The index,
j
, used to keep track of the current character instr2
.
We will use a 2D table, dp
, with rows and columns to store the result at any given state. represents the length of str1
and and represents the length of str2
. At any later time, if we encounter the same subproblem, we can return the stored result from the table with an lookup instead of recalculating that subproblem.
Let’s look at the following illustration to get a better understanding of the solution: