Longest Common Subsequence visualization

Longest sequence of characters appearing in both strings in the same order.

dp[i][j] = LCS length of the prefixes a[0..i) and b[0..j). Matching characters extend the diagonal by one; otherwise take the better of dropping a character from either string.

Edge cases: an empty string gives LCS 0; identical strings give their full length; no shared characters gives 0.

Complexity

Time: best O(m·n), average O(m·n), worst O(m·n). Space: O(m·n). Difficulty: Intermediate.

Pseudocode

procedure LCS(a, b):
  dp[0][*] ← 0; dp[*][0] ← 0
  for i ← 1 to m:
    for j ← 1 to n:
      if a[i] = b[j]: dp[i][j] ← dp[i−1][j−1] + 1
      else: dp[i][j] ← max(dp[i−1][j], dp[i][j−1])
  trace back diagonals to read the subsequence

More dynamic programming algorithms