CodingNodes / 2-D Dynamic Programming / Longest Common Subsequence System design Space play · ←→ step · R restart

Problem

A subsequence of a string is what remains after deleting zero or more of its letters, without changing the order of the rest. For example, "ace" is a subsequence of "apple".

Given two strings text1 and text2, return the length of the longest string that is a subsequence of both. If they share no letters, return 0.

Constraints

  • 1 ≤ text1.length, text2.length ≤ 1000
  • Both strings use lowercase English letters only

Examples: pick one to animate

Solutions

TimeO(m·n) SpaceO(m·n)

Time: The table has (m+1)·(n+1) cells and each is filled once with a comparison and at most one max.

Space: The whole (m+1) by (n+1) table is stored.

dp[i][j] is the answer for the first i letters of text1 and the first j letters of text2. If the last letters match, they extend the best answer of the shorter prefixes: dp[i-1][j-1] + 1. Otherwise drop one of them: max(dp[i-1][j], dp[i][j-1]). Row 0 and column 0 are 0.