AlgoViz

Longest Common Subsequence

Find the longest subsequence common to two sequences using dynamic programming.

IntermediateTime: O(m × n)Space: O(m × n)
Take Quiz
Step 1 / 0

Current Step

Click Play to start the visualization


## How Longest Common Subsequence Works

LCS finds the longest subsequence common to two sequences. A subsequence is a sequence that can be derived by deleting some elements without changing the order.

### Algorithm Steps:
1. Create a DP table of size (m+1) x (n+1)
2. For each cell (i, j):
- If characters match: dp[i][j] = dp[i-1][j-1] + 1
- If not: dp[i][j] = max(dp[i-1][j], dp[i][j-1])
3. Backtrack from dp[m][n] to find the actual LCS

### Key Characteristics:
- **2D DP Table**: Stores solutions to subproblems
- **Backtracking**: Reconstruct solution from the table
- **Applications**: Diff tools, DNA sequence alignment, version control

Time & Space Complexity

CaseTime Complexity
BestO(m × n)
AverageO(m × n)
WorstO(m × n)
SpaceO(m × n)

Practice Problems

10 problems81 total points
1

Longest Common Subsequence

Beginner5 pts
2

Longest Palindromic Subsequence

Beginner5 pts
3

Uncrossed Lines

Beginner5 pts
4

Minimum ASCII Delete Sum

Intermediate8 pts
5

Delete Operation for Two Strings

Intermediate8 pts
6

Edit Distance

Advanced10 pts
7

Shortest Common Supersequence

Advanced10 pts
8

Distinct Subsequences

Advanced10 pts
9

Interleaving String

Advanced10 pts
10

Regular Expression Matching

Advanced10 pts