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

Longest Common Subsequence

medium ~25 min

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. The tests include two 600-letter strings, so trying subsequences is far too slow; aim for O(m·n).

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