dp
with dimensions (len(str1) + 1) x (len(str2) + 1)
to store the lengths of LCS for substrings of str1
and str2
.dp
array using dynamic programming, where dp[i][j]
represents the length of LCS of str1[:i]
and str2[:j]
.str1
and str2
using indices i
and j
, starting from the end of the strings.str1[i]
and str2[j]
are equal, add this character to the LCS and move diagonally in the dp
array.dp
array (either up or left).dp
array is traversed.str1
and str2
, adding characters to the result string.str1
or str2
is not part of the LCS, add it to the result string before the matching LCS character.str1
or str2
to the result string.