☰ All problems

Longest Common Subsequence

Diff tools line up two versions of a text by finding what they have in common: the longest sequence of characters that appears in both versions in the same order, though not necessarily side by side. Everything outside that shared sequence is then shown as an insertion or a deletion.

Given two strings text1 and text2, return the length of their longest common subsequence, or 0 if they share no character. A subsequence keeps the order of the characters it uses but may skip any others: "rot" is a subsequence of "robot", while "tor" is not.

Example 1
Input: text1 = "draft", text2 = "drift"
Output: 4

Explanation: "drft" appears in order in both versions; only the vowel differs.

Example 2
Input: text1 = "release", text2 = "relapse"
Output: 6

Explanation: "relase" fits into both words in order, so six characters line up.

Example 3
Input: text1 = "moon", text2 = "fire"
Output: 0

Explanation: The two strings have no letter in common.

Constraints

  • text1 and text2 are each between 1 and 1000 characters long.
  • Both strings use only 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