Skip to main content
Interactive Algorithm Education

Visualize & Master Algorithms & Data Structures

Explore classic & modern sorting algorithms, efficient searching techniques, and interactive data structure visualizations — all with real-time step-by-step animation, comparisons, swaps, and Big-O metrics.

Dynamic Programming Visualizer

Longest Common Subsequence

Step 0 / 0
Speed 100ms
Step Progress 0 / 0
Table Size 0×0
Cells Filled 0
Status Ready
Uncomputed
Filling
Optimal path
0 / base case
Step Explanation

Select an algorithm and press Play to watch the table fill in.

—
Pseudocode
 

Longest Common Subsequence

Intermediate (3/5) ~45 minutes Sequence alignment DP on two strings Diagonal backtracking Optimal substructure Prereqs: Dynamic programming basics, Subsequences vs substrings
Quick Reference

Longest Common Subsequence

The Longest Common Subsequence problem finds the longest sequence of characters that appears in the same order in two strings (but not necessarily contiguously). Used in diff tools, bioinformatics, and version control.

Difficulty: Intermediate (3/5) dp

Complexity

Best Time
O(mn)
Average Time
O(mn)
Worst Time
O(mn)
Space
O(mn)

When to Use

For comparing sequences: file diffs, DNA/protein alignment, plagiarism detection, and edit-distance related problems.

Pros

  • Exact solution with clear DP formulation
  • Widely applicable to sequence comparison
  • O(mn) time is optimal for general strings

Cons

  • O(mn) space for reconstruction
  • Slow for very long strings
  • Returns length unless reconstructed carefully

History

The LCS problem was first studied in the 1970s and is a classic application of dynamic programming, appearing in the landmark 1974 paper by Hirschberg on optimal sequence alignment.

The Longest Common Subsequence (LCS) problem: find the longest sequence of characters that appears in the same order in both strings — not necessarily contiguously.

For example, ABCBDAB and BDCABA share the subsequence BCBA (length 4). It isn’t a substring of either, yet it appears in both, reading left to right.

This is the problem that powers diff, git merge, and DNA sequence alignment.

How It Works

The table dp[i][j] holds the LCS length of the first i characters of string A and the first j characters of string B:

  1. Initialize: the first row and column are 0 (an empty prefix shares nothing with anything).
  2. Match: if A[i-1] == B[j-1], extend the diagonal result: dp[i][j] = dp[i-1][j-1] + 1.
  3. Mismatch: otherwise carry the larger of the top and left neighbors:
    dp[i][j] = max(dp[i-1][j], dp[i][j-1])
  4. Reconstruct: walk the table from the bottom-right, following diagonals on matches.

Key Insight

The recurrence encodes a binary choice at every character pair:

  • Diagonal moves include a character in the LCS.
  • Up/left moves skip one.

Because any prefix’s best answer depends only on strictly smaller prefixes, filling row-by-row computes all answers — then a single backward walk recovers one concrete subsequence.

Worked Example

The visualizer runs the two strings A = ABCBDAB and B = BDCABA:

∅BDCABA
∅0000000
A0000111
B0111122
C0112222
B0112233
D0122233
A0122334
B0122344

The bottom-right cell reads 4, and the visualizer’s backtrack highlights B → C → B → A, yielding LCS = “BCBA”.

Edge Cases & Pitfalls

  • One empty string — every row/column value is 0: the LCS is empty.
  • Repeated characters — ties create multiple valid subsequences; backtracking picks one (e.g. BDAB is also valid here).
  • Subsequence ≠ substring — a substring is contiguous; LCS is order-only. Don’t mix up the two recurrences.
  • Long inputs — O(mn) memory for the full table. Length-only answers need just O(min(m, n)) via two rolling rows.

Comparison: LCS vs Edit Distance

AspectLCSEdit distance
QuestionLongest kept orderFewest edits
Match cost+10
Mismatchmax(skip)+1 (delete/insert/replace)
Relationedits = m + n − 2·LCS (insert/delete only)generalizes LCS

Applications

  • Version control — diff and git merge align files as LCS-style sequences
  • Bioinformatics — DNA and protein sequence alignment
  • Plagiarism detection — measuring document similarity

Practice Trajectory

  1. Hand-fill the table for two short strings and confirm the bottom-right value.
  2. Trace the backtrack to see why matches force a diagonal move.
  3. Distinguish LCS from the longest common substring recurrence.
  4. Reduce space to O(min(m, n)) for the length-only version.
  5. Adapt the recurrence into edit distance and verify the m + n − 2·LCS identity.