Dynamic Programming

Problem shape

Intermediate
4
8
15
16
23
42
Core idea

Compare prefixes of two strings and reuse overlap between states.

Step 1 / 5
Problem shape
Current lesson

Longest Common Subsequence Lab

Dynamic Programming Intermediate

Longest Common Subsequence

Welcome to the Longest Common Subsequence algorithm lab. Compare prefixes of two strings and reuse overlap between states. Use it when: Use for sequence similarity, diff tools, and edit-style matching. The time complexity is O(nm), and the space complexity is O(nm). The pseudocode is: if a[i] == b[j] dp[i][j] = 1 + dp[i - 1][j - 1] else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) As you practice, track the state that changes and the condition that makes the algorithm stop.

Time

O(nm)

Space

O(nm)

Pseudocode

if a[i] == b[j]
  dp[i][j] = 1 + dp[i - 1][j - 1]
else
  dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
Open deeper structure lesson
1.0x