Longest Common Subsequence

Medium#1143two strings

You get two words. A subsequence is what is left of a word after crossing out some of its letters, the order kept. Find the length of the longest subsequence the two words share. Our example: "plum" and "lump" share "lum", so the answer is 3.

input
text1, text2: two words of lowercase English letters.
returns
The length of the longest subsequence the two words share, 0 if none. A subsequence is what is left of a word after crossing out some of its letters, the order kept: "lum" is one of "plum".
constraints
  • 1 ≤ text1.length, text2.length ≤ 1000
  • text1 and text2 are lowercase English letters
our 12 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {string} text1
 * @param {string} text2
 * @return {number}
 */
function longestCommonSubsequence(text1, text2) {

}
Ctrl ↵
format
reset

saved in this browser

12 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more dynamic programming (dp) problems

Pattern “Dynamic programming (DP)” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.