Longest Common Sequence between two strings
Find the length of longest common subsequence of two given strings.
Assumptions
The two given strings are not null
Examples
S = “abcde”, T = “cbabdfe”, the longest common subsequence of s and t is {‘a’, ‘b’, ‘d’, ‘e’}, the length is 4.
High Level:
What to memo:
M[i][j] = longest length of subsequence from first i chars of s1, first j chars of s2
Base case:
M[0][j] = 0 and M[i][0] = 0
Induction rule:
if s1[i] == s2[j], M[i][j] = M[i-1][j-1] + 1
else M[i][j] = max(M[i-1][j], M[i][j-1])
TC: O(N^2) 2D memo
SC: O(N^2) 2D memo
Mistakes made:
top row and left most column do not all equal 0. It can inherit from neighbor if matched.
Last updated
Was this helpful?