Problem 513507 · medium · Level 05 Advanced Algorithms & Graphs

Longest Common Subsequence

dynamic programming · 2d dp · strings

Two-dimensional DP appears whenever the state needs two positions, for example one index into each of two strings. dp[i][j] then means "the answer for the first i characters of one string and the first j of the other".

A subsequence keeps some of a string's characters in their original order and drops the rest, so the kept characters need not be next to each other: "tale" is a subsequence of "table", but "late" is not. Write longest_common_subsequence(text1, text2) that returns the length of the longest string that is a subsequence of both text1 and text2, or 0 when they share no character.

Examples

Input:  text1 = "table", text2 = "tale"
Output: 4
Explanation: "tale" (skip the b of "table"); the longest common substring is only 2 long

Input:  text1 = "sky", text2 = "tree"
Output: 0

Constraints

  • 0 <= len(text1), len(text2) <= 500, lowercase letters only
  • Target: O(len(text1) * len(text2)) time

Goals

  • Set up a 2D DP table indexed by prefixes of two strings
  • Derive the match / no-match recurrence
  • Pad the table with an extra row and column so base cases need no special handling
Starting Python…