Longest Common Subsequence

Medium2-D dynamic programming

Given two strings text1 and text2, return the length of the longest string that is a subsequence of both, or 0 if they share no letter.

A subsequence keeps some of a string’s characters in their original order, not necessarily next to each other: "ace" is a subsequence of "abcde".

Examples

Example 1
Input:  text1 = "kitten", text2 = "sitting"
Output: 4

ittn is in both, in order.

Example 2
Input:  text1 = "pqr", text2 = "xyz"
Output: 0

The two strings share no letter.

Constraints

  • 1 ≤ text1.length, text2.length ≤ 1000
  • Both strings hold lowercase English letters only.

Stuck?

Hint 1

Compare the last characters. If they match, they end the common subsequence; if not, drop the last character of one string or the other and keep the better result.

Hint 2

Fill a table where dp[i][j] is the answer for the first i letters of text1 and the first j of text2: a match is dp[i - 1][j - 1] + 1, otherwise max(dp[i - 1][j], dp[i][j - 1]).

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur