#1143

Longest Common Subsequence

Medium 2D DP on two strings

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the length of the longest sequence of characters that appears in both strings in the same order (not necessarily contiguous).

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the longest sequence of letters in both strings, in order.

Why this works: dp[i][j] for prefixes: equal last letters → 1 + diagonal; otherwise the better of dropping a letter from either string.

Example: "abcde" and "ace"

matches a, c, e → 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Confusing subsequence with substring and resetting to 0 on a mismatch.

Solve on LeetCode ↗
Complexity
  • Time: O(n·m).
  • Space: O(n·m), reducible to O(m).
Topic: Dynamic Programming
🎬 Episodes 86–96: video coming soon