Algorithms · Visualized

DP: Longest Common Subsequence

Dynamic Programming

Break problems into overlapping subproblems and store answers.

Finds the length of the longest subsequence common to two strings (characters don't need to be contiguous, but must appear in the same relative order in both). Time: O(n × m) average, O(n × m), where n, m are the lengths of the two strings worst; space: O(n × m), reducible to O(min(n,m)) with a rolling array.

Big-O: The most-asked interview category — 35 classics here.

Longest Common Subsequence

Dynamic Programming

Finds the length of the longest subsequence common to two strings (characters don't need to be contiguous, but must appear in the same relative order in both). dp[i][j] represents the LCS length between the first i characters of one string and the first j characters of the other, built from smaller prefixes.

How Longest Common Subsequence Works

  1. Create a DP table with dimensions (len1+1) × (len2+1), initialized to 0 along the first row and column (an empty string has LCS length 0 with anything).
  2. For each pair of positions (i, j), check if the characters at string1[i-1] and string2[j-1] match.
  3. If they match, dp[i][j] = dp[i-1][j-1] + 1 (extend the LCS found without these characters by one).
  4. If they don't match, dp[i][j] = max(dp[i-1][j], dp[i][j-1]) — take the best LCS achievable by dropping a character from either string.
  5. Continue filling the table; dp[len1][len2] holds the final LCS length.

Longest Common Subsequence Worked Example

Input: {text1: abcde, text2: ace}

Building the table: 'a' matches 'a' → dp grows. 'c' matches 'c' further along → extends further. 'e' matches 'e' at the end → extends once more. The characters a, c, e appear in order in both strings, giving a longest common subsequence 'ace' with length 3.

DP: Longest Common SubsequenceO(m·n)
LCS of two strings.
·ace
·0000
a0000
b0000
c0000
d0000
e0000
a
b
c
d
e
01234
a
c
e
012
Step 1 / 17
Default Current / Compare Swap / Write Settled Active / Path Pivot / Reject Locked (hollow) Target
Longest Common Subsequence: match → 1 + diag; mismatch → max(skip one).
Python · Dynamic Programming Algorithms in Code
def lcs(a, b):
    n, m = len(a), len(b)
    dp = [[0] * (m + 1) for _ in range(n + 1)]
    for i in range(1, n + 1):
        for j in range(1, m + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[n][m]

Behind the Scenes Execution

Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.

Longest Common Subsequence Time & Space Complexity

BestO(n × m)
AverageO(n × m)
WorstO(n × m), where n, m are the lengths of the two strings
SpaceO(n × m), reducible to O(min(n,m)) with a rolling array

When to Use Longest Common Subsequence

  • The core algorithm behind 'diff' tools (comparing file versions), DNA sequence alignment in bioinformatics, and plagiarism detection.

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits

Keep the momentum going

Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.