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:

Input:
word1 = "abcde"
word2 = "ace"
Output: 3
Explanation:

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

Example 2:

Input:
word1 = "almost"
word2 = "algomonster"
Output: 6
Explanation:

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

Example 3:

Input:
word1 = "abc"
word2 = "def"
Output: 0
Explanation:

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

Try it yourself

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro