Longest Common Subsequence (LCS)
Software Engineer path · lesson 36 of 99Finds the longest subsequence present in both sequences (not necessarily contiguous).
Compare "ABCBDAB" with "BDCABA". The first row and column are 0 (an empty string shares nothing).
- 1dp[0][*] = dp[*][0] = 0
- 2for i in 1..len(a), for j in 1..len(b):
- 3 if a[i-1] == b[j-1]: dp[i][j] = dp[i-1][j-1] + 1 # match: diagonal
- 4 else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) # drop one char
- 5walk back from dp[m][n] to read the subsequence
- Cells filled
- 0 / 42
- Matches
- 0 / 12
LCS so far: …
Tap any element in the diagram to inspect its state at this step.
Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.
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
References & Further Reading
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