Longest Common Subsequence Visualizer

Compare two strings, fill the longest common subsequence DP table, and backtrack one valid LCS result.

First
7
Second
6
LCS length
4
Step
1

String input

Step controls

Start with an LCS table for 7 by 6 characters.

LCS table

Current operation: Start

Current Candidates LCS path
First / second0BDCABA
00000000
A0
B0
C0
B0
D0
A0
B0

LCS output

row = 0
col = 0
operation = Start
lcs_length = 4
sequence = BCBA

Backtracked sequence

1: B2: C3: B4: A

What is a Longest Common Subsequence Visualizer?

A longest common subsequence visualizer shows the longest sequence of characters that appears in two strings in the same relative order. The characters do not need to be contiguous.

This tool lets you enter two strings, fill the LCS dynamic programming table, and backtrack one valid longest common subsequence.

For the full algorithm set, browse the Data Structure Visualizers hub.

How to use this LCS visualizer

  • Enter the first string.
  • Enter the second string.
  • Click Run LCS to fill the table and show the final subsequence.
  • Step forward to inspect each match, top-cell reuse, or left-cell reuse.
  • Read the backtracked sequence and length in the output panel.

LCS and dynamic programming

LCS is a standard dynamic programming problem because each table cell depends on smaller prefixes of the two strings. A character match takes the diagonal value plus one; a mismatch keeps the better of the top and left cells.

For related table-based string DP, compare this page with the Edit Distance Visualizer. To practice another reusable-subproblem DP pattern, try the Coin Change DP Visualizer. For non-DP string matching, use the KMP String Matching Visualizer.

Frequently Asked Questions

What does subsequence mean?
A subsequence keeps characters in order but may skip characters between them.
What does each LCS table cell mean?
Cell dp[i][j] stores the length of the longest common subsequence between the first i characters of string A and the first j characters of string B.
Can there be more than one LCS?
Yes. Two strings can have multiple longest common subsequences with the same length. This tool backtracks one valid answer.
What is the time complexity of LCS?
The standard dynamic programming algorithm runs in O(mn) time and O(mn) space for strings of length m and n.

Related tools