Algorithms · Visualized
DP: Longest Common Subsequence
Dynamic Programming
Break problems into overlapping subproblems and store answers.
Finds the length of the longest subsequence common to two strings (characters don't need to be contiguous, but must appear in the same relative order in both). Time: O(n × m) average, O(n × m), where n, m are the lengths of the two strings worst; space: O(n × m), reducible to O(min(n,m)) with a rolling array.
Big-O: The most-asked interview category — 35 classics here.
Longest Common Subsequence
Dynamic ProgrammingFinds the length of the longest subsequence common to two strings (characters don't need to be contiguous, but must appear in the same relative order in both). dp[i][j] represents the LCS length between the first i characters of one string and the first j characters of the other, built from smaller prefixes.
How Longest Common Subsequence Works
- Create a DP table with dimensions (len1+1) × (len2+1), initialized to 0 along the first row and column (an empty string has LCS length 0 with anything).
- For each pair of positions (i, j), check if the characters at string1[i-1] and string2[j-1] match.
- If they match, dp[i][j] = dp[i-1][j-1] + 1 (extend the LCS found without these characters by one).
- If they don't match, dp[i][j] = max(dp[i-1][j], dp[i][j-1]) — take the best LCS achievable by dropping a character from either string.
- Continue filling the table; dp[len1][len2] holds the final LCS length.
Longest Common Subsequence Worked Example
Input: {text1: abcde, text2: ace}
Building the table: 'a' matches 'a' → dp grows. 'c' matches 'c' further along → extends further. 'e' matches 'e' at the end → extends once more. The characters a, c, e appear in order in both strings, giving a longest common subsequence 'ace' with length 3.
| · | a | c | e | |
|---|---|---|---|---|
| · | 0 | 0 | 0 | 0 |
| a | 0 | 0 | 0 | 0 |
| b | 0 | 0 | 0 | 0 |
| c | 0 | 0 | 0 | 0 |
| d | 0 | 0 | 0 | 0 |
| e | 0 | 0 | 0 | 0 |
def lcs(a, b):
n, m = len(a), len(b)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[n][m]Behind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Longest Common Subsequence Time & Space Complexity
When to Use Longest Common Subsequence
- The core algorithm behind 'diff' tools (comparing file versions), DNA sequence alignment in bioinformatics, and plagiarism detection.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.