Intermediate Topic 27 of 51 Algorithms
Longest Common Subsequence
Finding the longest shared ordered subsequence of two sequences.
How it works
The longest common subsequence of two sequences is the longest sequence that appears in both in the same order, not necessarily contiguous. A dynamic programming table L[i][j] stores the answer for the first i and j characters: matching characters extend the diagonal value by one, otherwise take the maximum of the left and upper cells. Time and space are O(mn), and space can be reduced with rolling rows.
Where it is used
The diff tool and version control, DNA and protein comparison, plagiarism detection and file synchronization use LCS to compare sequences.
Common pitfall
Confusing subsequence with substring, which must be contiguous, is common. Recovering the actual sequence requires walking back through the table. For very large inputs, O(mn) memory is a problem, which Hirschberg's algorithm addresses. Handle empty strings in the base row and column.
Where it fits in the course
Longest Common Subsequence is topic 27 of 51 in Algorithms, rated Intermediate. It follows Knapsack Problem. The next topic is Edit Distance.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Algorithms quiz.
- Explore the DP Table (LCS) visualizer: Watch the longest common subsequence table fill.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Algorithms quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Longest Common Subsequence?
Where do people use Longest Common Subsequence?
What is the most common mistake with Longest Common Subsequence?
What should I learn before this topic?
How can I practice it?
Is Longest Common Subsequence hard to learn?
How long does it take to learn Longest Common Subsequence?
Which topics are related to Longest Common Subsequence?
What should I study after Longest Common Subsequence?
Related topics
- Knapsack Problem (Algorithms)
- Edit Distance (Algorithms)
- Dynamic Programming (Algorithms)
- Backtracking (Algorithms)
- Common Table Expressions (Databases)