Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming/LCS / Two-Sequence

Learn the pattern · ~14 min

LCS / Two-Sequence

also called edit distance, alignment DP

Put one string on each axis of a grid. Each cell answers "the first i of A against the first j of B", using only the cell up, the cell left and the diagonal.

Signalstwo strings/arrays compared, aligned, or interleavedminimum editscount occurrences as a subsequenceLearn first1D / Fibonacci-style
Cheat sheet and practice

Reach for it when you read

  • +Two strings (or two arrays) and "the longest common…", "the fewest edits", "how many ways to match".
  • +"Delete / insert characters until the two strings are equal": the answer comes from their LCS.
  • +Matching with wildcards (., *, ?): each pattern letter against each text letter.
  • +Lines drawn between equal values of two rows that may not cross: LCS in disguise.
  • +Your recursion takes two indices, one per string, and moves one or both each step.

Not this one when

  • ×One string against itself (longest palindromic substring, fewest cuts into palindromes): interval / palindrome DP over [i, j].
  • ×Find where a fixed pattern occurs in a text, no edits: string matching (KMP, Z, hashing).
  • ×Longest common substring of many strings, or huge strings: suffix structures or binary search plus hashing, not an n × m table.

Learn LCS / Two-Sequence

First, what does "subsequence" mean?

A subsequence keeps some letters of a string, in their order, and may skip any in between. From "trace" you can get "tae" (skip r and c) or "rce". You can't get "art": in "trace" the a comes after both r and t.

A substring is stricter: no gaps. "rac" is a substring of "trace", "tae" isn't.

A common subsequence comes from both strings; the longest is the LCS.

The problem: longest common subsequence

a = "trace", b = "crate". How long is their LCS? Try by hand:

candidate in "trace"? in "crate"? how you found it
"ce" t r a c e c r a t e c then e in both
"rat" r a, but no t after them r a t fails in "trace"
"rae" t r a c e c r a t e r, a, e in order in both

"rae", length 3. But checking every subsequence of one string against the other means 2ⁿ candidates.

One choice at the last letters

If the last letters are equal, pair them: 1 + the answer without both. If they differ, one of them isn't in the answer: drop a's last letter, or drop b's, and keep the better.

Write L(i, j) for "the LCS of the first i letters of a and the first j letters of b". Start at L(5, 5):

call last letters what happens
L(5, 5): "trace" vs "crate" e, e equal: pair them, 1 + L(4, 4)
L(4, 4): "trac" vs "crat" c, t differ: max(L(3, 4), L(4, 3))
L(i, 0) or L(0, j) none an empty string shares nothing: 0

Why may we pair equal last letters right away? Take any best answer that doesn't pair them. If it uses neither, it isn't best: add the pair at the end and it grows. If it uses one, say a's last e matched with an earlier e in b, swap that partner for b's last e: same length, now paired. So pairing is never worse.

The brute force: the plain recursion

C++
// L(i, j) = LCS of the first i letters of a and the first j letters of b
int L(int i, int j, const string& a, const string& b) {
    if (i == 0 || j == 0) return 0;                  // an empty prefix shares nothing
    if (a[i - 1] == b[j - 1])
        return 1 + L(i - 1, j - 1, a, b);            // last letters match: pair them
    return max(L(i - 1, j, a, b),                    // drop a's last letter
               L(i, j - 1, a, b));                   // or drop b's
}

It returns 3. The top of its tree:

  • L(5, 5) "trace" vs "crate": e = e, pair
    • L(4, 4) "trac" vs "crat": c ≠ t
      • drop c: L(3, 4) "tra" vs "crat": a ≠ t
        • L(2, 4) …
        • L(3, 3) "tra" vs "cra"← here
      • drop t: L(4, 3) "trac" vs "cra": c ≠ a
        • L(3, 3) "tra" vs "cra"← and here
        • L(4, 2) …

Every mismatch splits in two: with no letter in common, 16-letter strings already take 1.4 seconds and 20-letter ones make 2.8 × 10¹¹ calls. The problem allows 1000. Time limit exceeded.

The one thought: the same question comes back

Dropping c then t, or t then c, both leave "tra" vs "cra": L(3, 3). Same two prefixes, same answer (2, from "ra"), worked out twice. Lower down, L(2, 2) comes up 4 times and L(1, 1) 6 times.

A call is fixed by two numbers, the prefix lengths: only (n + 1)(m + 1) different questions, 36 here, about 10⁶ for two 1000-letter strings. Write each answer down:

C++
int L(int i, int j, const string& a, const string& b, vector<vector<int>>& memo) {
    if (i == 0 || j == 0) return 0;
    int& m = memo[i][j];
    if (m != -1) return m;                           // this pair of prefixes was answered before
    if (a[i - 1] == b[j - 1]) return m = 1 + L(i - 1, j - 1, a, b, memo);
    return m = max(L(i - 1, j, a, b, memo), L(i, j - 1, a, b, memo));
}

Bottom-up: fill the table row by row

L(i, j) reads only up, left and up-left, so fill the table row by row from the top-left, and every cell it needs is ready.

C++
int lcs(const string& a, const string& b) {
    int n = a.size(), m = b.size();
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));   // row 0, column 0: an empty prefix
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            dp[i][j] = a[i - 1] == b[j - 1] ? dp[i - 1][j - 1] + 1              // pair them
                                            : max(dp[i - 1][j], dp[i][j - 1]);   // drop one
    return dp[n][m];
}

Row 3 (the a of "trace"), with the row above 0, 1, 1, 1, 1:

j b's letter what happens dp[3][j]
1 c a ≠ c: max(up 0, left 0) 0
2 r a ≠ r: max(up 1, left 0) 1
3 a a = a: up-left 1, plus 1 2
4 t a ≠ t: max(up 1, left 2) 2
5 e a ≠ e: max(up 1, left 2) 2

The whole table (the zero row and column left out):

c r a t e
t 0 0 0 1 1
r 0 1 1 1 1
a 0 1 2 2 2
c 1 1 2 2 2
e 1 1 2 2 3

The corner is 3, the same answer as the brute force. To get the letters, walk back from it: on a match, write the letter and go up-left; otherwise step toward the bigger neighbour (either on a tie). That spells "rae".

Why it's O(n × m)

Count the cells, not the loops: (n + 1)(m + 1), each filled once with one comparison and a max. O(n × m) time, 10⁶ steps for two 1000-letter strings. Space is O(n × m), or O(m) with two rows, since a row reads only itself and the one above.

From 2.8 × 10¹¹ calls down to 441 cells for two 20-letter strings, because a question is only "which two prefixes?"

Edit distance? Same table, three moves

The fewest inserts, deletes and replaces that turn "trace" into "crate"? A matching last letter costs nothing (up-left). Otherwise pay 1 for the cheapest move: replace (up-left), delete a's letter (up), insert b's letter (left). The edges change too: i letters to nothing takes i deletes.

C++
int minDistance(const string& a, const string& b) {
    int n = a.size(), m = b.size();
    vector<vector<int>> dp(n + 1, vector<int>(m + 1));
    for (int i = 0; i <= n; i++) dp[i][0] = i;       // delete all i letters
    for (int j = 0; j <= m; j++) dp[0][j] = j;       // insert all j letters
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            dp[i][j] = a[i - 1] == b[j - 1] ? dp[i - 1][j - 1]          // match: free
                     : 1 + min({dp[i - 1][j - 1],                       // replace
                                dp[i - 1][j],                           // delete a's letter
                                dp[i][j - 1]});                         // insert b's letter
    return dp[n][m];
}
c r a t e
t 1 2 3 3 4
r 2 1 2 3 4
a 3 2 1 2 3
c 3 3 2 2 3
e 4 4 3 3 2

2: replace t → c and c → t.

Delete letters until they match? Use the LCS

Keep the LCS, delete the rest: n + m − 2 × LCS = 5 + 5 − 6 = 4.

Remember this

  • Two strings and "longest common", "fewest edits", "how many ways to match": a table over prefix pairs, dp[i][j].
  • Row 0 and column 0 are the empty prefix, so letters are a[i − 1] and b[j − 1]. Off-by-one here is the classic bug.
  • Equal letters: up-left. Different: the best of the neighbours (LCS) or 1 + the cheapest of three (edit distance).
  • Substring instead of subsequence: a mismatch sets the cell to 0, and the answer is the biggest cell anywhere (2 here, "ra").
  • Whenever a problem compares two sequences letter by letter and can skip in either one, it's this table.

Practise it on Longest Common Subsequence, then Delete Operation for Two Strings (n + m − 2 × LCS), Uncrossed Lines (LCS in disguise), Edit Distance (three moves), Shortest Common Supersequence (walk back from the corner) and Distinct Subsequences (count instead of max).

Below, watch Longest Common Subsequence run line by line.

Watch it work, line by line

Longest Common Subsequence ↗, text1 = "abcde", text2 = "ace" → 3 ("ace"). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Am I comparing two sequences, where each step either matches the current items or skips one of them, and are both short enough for an n × m table?

Reach for it when

  • +two strings/arrays compared, aligned, or interleaved
  • +minimum edits
  • +count occurrences as a subsequence
  • +|a|*|b| up to ~1e7

It fails when

  • ×One sequence with self-structure (increasing run, palindrome)use LIS or palindrome DP
  • ×Longest common substring (contiguous) — you're confusing it with subsequenceuse Same grid, reset to 0 on mismatch
  • ×Sequences so large the O(n·m) table doesn't fituse Hirschberg or hashing
  • ×One string tiny, the other huge (is it a subsequence?)use Greedy subsequence check / automaton
  • ×LCS of two permutationsuse Reduce to LIS in O(n log n)

Looks like it, isn't (and the other way round)

  • Minimum Total Distance Traveled looks like Greedy, needs this pattern

    Nearest-factory greedy fails on capacities. After sorting, an optimal matching is non-crossing, which gives a two-sequence DP (editorial memoisation).

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1What does dp[i][j] mean in LCS?Reveal

    The length of the longest common subsequence of the first i letters of A and the first j letters of B.

  • 2Why the diagonal on a match, and not up or left?Reveal

    Pairing the two last letters uses both of them, so what remains is both prefixes without them: dp[i-1][j-1].

  • 3How does longest common substring differ?Reveal

    A mismatch resets the cell to 0 instead of taking max(up, left), and the answer is the biggest cell anywhere.

  • 4On a match, why don't you also try dropping one of the two matching letters?Reveal

    Some longest answer always pairs them: if it ended with a different letter you could append the match, and if it used earlier copies you can re-pair them with the last ones. Dropping one can't do better.

Practice ladder

every problem →
  1. 1Longest Common Subsequencethe hookMedium
  2. 2Delete Operation for Two Stringscount deletionsMedium
  3. 3Uncrossed Linesstory stripMedium
  4. 4Edit Distanceedit distanceMedium
  5. 5Edit Distanceedit distanceMedium
  6. 6Interleaving Stringa third stringMedium
  7. 7Shortest Common Supersequence rebuild the answerHard
  8. 8Distinct SubsequencescountHard
  9. 9Regular Expression MatchingwildcardsHard

Finished LCS / Two-Sequence? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to LCS / Two-Sequence

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial