progress

~/problems / 2-D dynamic programming / String DP (edit distance, LCS)

Longest Common Subsequence

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or play this problem's boss fight .

Write longest_common_subsequence(text1: str, text2: str) -> int: the length of the longest string that is a subsequence of both inputs. A subsequence keeps some characters in their original order, not necessarily next to each other. Return 0 if nothing is shared.

Examples:

  • longest_common_subsequence("stone", "longest") == 3 ("one")
  • longest_common_subsequence("abc", "cba") == 1
  • longest_common_subsequence("xyz", "pqr") == 0

Constraints: each string has 1 to 1000 lowercase letters.

⭐ Bonus: a speed test with two 600-letter strings earns a star in O(m·n). Trying subsequences is far too slow for it.

Show hint

compare the answer for prefixes text1[:i] and text2[:j] with the answers for slightly shorter prefixes, depending on whether their last letters are equal.

Topic: String DP (edit distance, LCS). dp[i][j] over prefixes of two strings; palindromes by expanding or by length.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc