Longest Common Subsequence (LCS)
Finds the longest subsequence present in both sequences (not necessarily contiguous).
Longest Common Subsequence (LCS)
Finds the longest subsequence present in both sequences (not necessarily contiguous).
| Ø | A | C | E | |
|---|---|---|---|---|
| Ø | 0 | 0 | 0 | 0 |
| A | 0 | 0 1,1 | 0 | 0 |
| B | 0 | 0 | 0 | 0 |
| C | 0 | 0 | 0 | 0 |
| D | 0 | 0 | 0 | 0 |
| E | 0 | 0 | 0 | 0 |
Scroll horizontally to see the full table
Comparing s1[0] ('A') with s2[0] ('A')
The LCS recurrence
Fill in what each case of the LCS table stores.
Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.
Compare a[i] with b[j]
Test your knowledge
If characters match at dp[i][j], where does the value come from?
The short version
Think of comparing two DNA sequences. You want to find the longest strand of matching genetic code that appears in the same order in both, even if there are 'junk' genes in between.
In more depth
String Alignment
LCS is the mother of all "String Comparison" DP problems. It aligns two strings to find the maximum matching characters while keeping their relative order.
2D Grid Intuition:
We compare char A[i] and B[j]:
This logic underpins 'diff' tools in Git!
When to reach for this
- Compare two strings to find similarities/differences
- Edit distance / Mutation distance
- Longest Palindromic Sequence (LCS of string and its reverse)
Interview Questions
Love this visualization?
Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.
100% free • No credit card required