longest-common-subsequence.sh — zsh
stringsdynamic-programming

Given two strings text1 and text2, return the length of their longest common subsequence. A subsequence keeps the original left-to-right order of characters, but the chosen characters do not need to be adjacent.

Input / output

  • Input: text1: str, text2: str
  • Output: int — the length of the longest subsequence common to both strings

Examples

  1. text1 = "abcde", text2 = "ace" returns 3 because "ace" is a common subsequence.
  2. text1 = "abc", text2 = "abc" returns 3 because the entire string matches.
  3. text1 = "abc", text2 = "def" returns 0 because they share no characters in order.

Constraints

  • 0 <= text1.length, text2.length <= 1000
  • text1 and text2 contain only lowercase English letters

Follow-up How would you reconstruct one actual longest common subsequence string, not just its length? Can you reduce the dynamic-programming table from O(m * n) space to O(min(m, n)) space?

Examples
Example 1
Input: text1 = "abcde", text2 = "ace"
Output: 3
Example 2
Input: text1 = "abc", text2 = "abc"
Output: 3
Example 3
Input: text1 = "abc", text2 = "def"
Output: 0