☰ All problems

69. Longest Common Subsequence

Given two strings text1 and text2, return the length of their longest common subsequence, or 0 if they share no characters.

A subsequence is what remains after deleting any number of characters (possibly none) without changing the order of the rest. For example, "one" is a subsequence of "stone". A common subsequence is one that is a subsequence of both strings.

Example 1
Input: text1 = "stone", text2 = "longest"
Output: 3

Explanation: "one" appears in order in both strings, and no common subsequence of length 4 exists.

Example 2
Input: text1 = "abc", text2 = "abc"
Output: 3
Example 3
Input: text1 = "abc", text2 = "def"
Output: 0

Constraints

  • 1 <= text1.length, text2.length <= 1000
  • Both strings consist of lowercase English letters

Follow-up: Reconstruct one longest common subsequence itself, not just its length.

💡 Hint 1

Compare the last characters. If they are equal, they can end the common subsequence. If not, one of them is not part of it.

💡 Hint 2

Let dp[i][j] be the answer for the first i characters of text1 and the first j of text2. Then dp[i][j] = dp[i-1][j-1] + 1 on a match, else max(dp[i-1][j], dp[i][j-1]).

💡 Hint 3

Each row only depends on the previous one, so two rows of length n + 1 are enough.

/**
 * @param {string} text1
 * @param {string} text2
 * @return {number}
 */
function longestCommonSubsequence(text1, text2) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc