Lesson 77 of 86AdvancedPro Interactive Lesson

Longest Common Subsequence (LCS)

Compare pairs of prefixes. At matching characters, extend the result for the two shorter prefixes.

Core Intuition & How It Works

Longest Common Subsequence (LCS) measures the longest sequence appearing in the same relative order in two strings. A 2D DP table matches characters diagonally (1 + dp[i-1][j-1]) or takes the better skip (max of top or left).

In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.

Time & Space Complexity

MetricComplexity
Time ComplexityO(m × n)
Space ComplexityO(m × n) or O(min(m, n))
Topic ChapterChapter 13: Dynamic Programming
Difficulty LevelAdvanced

Key Pattern to Recognize

Pad the DP table with an extra row and column of zeros at index 0 so empty-prefix base cases require no conditionals.

Common Pitfalls & Edge Cases

Confusing subsequence (non-contiguous) with substring (contiguous, which resets to 0 on mismatch).

Real-World & Technical Interview Applications

Git diff / patch generation, DNA/protein sequence alignment, and plagiarism detection.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.