Longest Common Subsequence

Given two strings word1 and word2, determine the length of the longest common subsequence between the two strings.

A subsequence consists of characters from the original string that appear in the same order but may not be consecutive. For instance, "ace" is a valid subsequence of "abcde", but "aec" is not. More formally, a subsequence of a string is derived by deleting zero or more characters from the original string, without altering the relative order of the remaining characters.

A common subsequence of two strings is a string that is a subsequence of both strings.

If the two strings share no common subsequences, the answer is 0.

Example 1:

1word1 = "abcde"
2word2 = "ace"
Output: 3

The longest common subsequence is ace and its length is 3.

Example 2:

1word1 = "almost"
2word2 = "algomonster"
Output: 6

The longest common subsequence is almost and its length is 6.

Example 3:

1word1 = "abc"
2word2 = "def"
Output: 0

There is no such common subsequence, so the result is 0.

Try it yourself

↑TA πŸ‘¨β€πŸ«