Scrivio Interview library
Dynamic programmingDynamic programmingReported 20 times · 14 min read · updated 14 November 2026

Find the length of the longest common subsequence of two strings using dynamic programming.

1What a common subsequence is, told with two travel diaries

Imagine two friends who took the same long train journey and each kept a diary of the stations they noticed. One wrote down more stations than the other, and each missed a few the other saw, but neither ever wrote two stations in the wrong order. If we want to know how much of the journey their diaries agree on, we look for the longest list of stations that appears in both diaries in the same order. That list is their longest common subsequence.

A subsequence of a string is what is left after rubbing out some of its letters, without moving the others. For abcde, rubbing out b and d leaves ace, so ace is a subsequence of abcde. But aec is not, because in abcde the e comes after the c, and we are not allowed to reorder. The letters of a subsequence need not sit next to each other; that is what makes it different from a substring, which must be one unbroken piece.

The longest common subsequence, LCS for short, of two strings is the longest string that is a subsequence of both. We are asked only for its length. Our example is abcde and ace. The whole of ace can be found inside abcde in order, so the answer is 3. For ABCBDAB and BDCABA the answer is 4, for example BCBA, and for abc and def it is 0, since they share no letter at all.

PictureThe two strings, with their common subsequence marked

Top: abcde. Bottom: ace. The marked letters a, c, e appear in both, in the same order.

  1. abcdeace

    1Reading both strings left to right, a, c and e appear in both in the same order, so the answer is 3. The b and d are simply skipped.

What to assume

Do we return the length or the string itself?
The length.
Is the comparison case sensitive?
Yes, a and A are different letters.
How long can the strings be?
Up to a few thousand letters each. And with an empty string the answer is simply 0.

The problem looks big because there are so many ways to rub letters out. A string of 5 letters has 32 subsequences and one of 20 letters has over a million. But we will soon see that the question is really about far fewer things than that, which is why it can be solved quickly.

A careful candidate asks a few questions. Do we return the length or the string itself? The length, and the FAQs show how to rebuild the string. Is the comparison case sensitive? Yes, a and A are different letters. How long can the strings be? Up to a few thousand letters each, so a table of a few million numbers is affordable. And with an empty string the answer is simply 0.

2How to recognise a dynamic programming problem

A beginner's first idea is often to walk both strings with two fingers, moving both on a match. That works until the letters differ. Then which finger should move? If we move the wrong one, we may skip a letter that would have matched later. A fixed rule, such as always moving the first finger, gives wrong answers, and that uncertainty is the first clue.

The first clue, then, is a choice at every mismatch: we may drop the current letter of the first string or of the second, and we cannot tell in advance which is better. When a problem forces a choice at each step and we cannot decide it locally, we usually have to consider both options and keep the better result.

The second clue appears when we try both options. Dropping a letter of the first string and then of the second leaves exactly the same pair of shorter strings as dropping them the other way round. Different orders of choices lead to the same smaller problem. This is called overlapping subproblems, and it means a plain search would solve the same small problem many times.

A choice at each step plus overlapping subproblems is the signal for dynamic programming. The name is old and not very descriptive; it simply means solving a problem by combining answers to smaller versions of it, computing each smaller answer once and writing it in a table so it is never computed again. The rule to carry to new problems is that when the input is two strings, the smaller problems are almost always pairs of prefixes, the first i letters of one and the first j of the other, and the table is a grid with one cell per pair.

Similar patterns do not fit. Two pointers that walk both strings are enough to check whether one string is a subsequence of the other, because there a match can always be taken at once, but for the longest common one they would have to guess on every mismatch. A sliding window needs one unbroken range, and a subsequence is not one.

3The honest first attempt, a brute force that tries both choices

The honest first attempt follows the two-finger idea and simply refuses to guess. We compare the letters at positions i and j. If they match, that letter can belong to the answer, so we count it and move both fingers. If they differ, at least one of them is not in the answer, so we try both: once without the letter of a, once without the letter of b, and keep the better result. When either string runs out, nothing more can be shared, so we return 0.

Step throughThe calls the plain recursion makes for abc and def

Each node is a call lcsFrom(i, j). On a mismatch it calls itself twice, skipping a letter of a on the left and of b on the right.

  1. 0,01,00,1

    1The first call compares a with d. They differ, so it tries skipping a, which is (1,0), and skipping d, which is (0,1).

  2. 0,01,00,12,01,11,10,2

    2Each of those calls differs again and splits again. Already, (1,1) appears twice: skip a then d, or skip d then a.

  3. 0,01,00,12,01,11,10,23,02,12,11,22,11,21,20,3

    3One level more and (2,1) and (1,2) appear three times each. Every repeat redoes the same work, all the way down.

Java
// LCS of a[i..] and b[j..], trying both choices on every mismatch.
static int lcsFrom(String a, String b, int i, int j) {
if (i == a.length() || j == b.length()) return 0; // one string is used up
if (a.charAt(i) == b.charAt(j)) return 1 + lcsFrom(a, b, i + 1, j + 1);
return Math.max(lcsFrom(a, b, i + 1, j), lcsFrom(a, b, i, j + 1));
}

Let us do it by hand on abcde and ace. a and a match, so we count 1 and compare bcde with ce. b and c differ, so we try cde with ce and bcde with e. The first path matches c, then compares de with e, skips d, matches e: 1 + 1 + 1 = 3. The method returns 3, the right answer, after 15 calls.

Where is the waste? It shows most clearly on two strings with nothing in common, where every comparison is a mismatch and every call splits into two. The picture shows the calls for abc and def.

4From the repeated calls to a table filled once

Look at the picture again. A call is fully described by its pair (i, j); nothing else changes. For abc and def there are only 15 different pairs, yet the recursion made 39 calls. For two 10-letter strings with nothing in common it makes 369,511 calls, while there are only 120 different pairs. The time grows roughly like 2 to the power m + n, where m and n are the lengths, and almost all of it is repeated work.

The middle step is called memoisation, which means writing each answer down the first time it is found. We keep the same recursion, but store the answer for each pair in an array and return it at once if the pair comes up again. Each pair is then solved once, so the time drops to about m x n. Its weakness is recursion depth, which for long strings can overflow Java's stack.

The final step fills the same table from the bottom up with a plain loop. It is easier to read with prefixes, so let dp[i][j] be the LCS length of the first i letters of a and the first j letters of b. Row 0 and column 0 are 0, because an empty prefix shares nothing. For any other cell we look at the last letter of each prefix, a[i-1] and b[j-1].

If the last letters are equal, the best common subsequence can end with that letter, so dp[i][j] = dp[i-1][j-1] + 1, the cell diagonally up and to the left, plus one. If they differ, both cannot be the last letter of a common subsequence, so one of them can be dropped, and we take the better of the two smaller problems: dp[i][j] = max(dp[i-1][j], dp[i][j-1]), the larger of the cell above and the cell to the left.

Here a beginner should ask, is it always safe to take the match? Could skipping a matching pair ever give a longer answer? It cannot. Take any common subsequence that does not use the final matching letter. Its last letter can be swapped for that matching pair, which comes later in both strings, without making it shorter, so matching never loses. And each cell needs only the cell above, the cell to the left and the diagonal, so filling row by row, left to right, always has them ready.

5Watching the table fill for abcde and ace

The picture fills the real table. Rows are prefixes of abcde and columns prefixes of ace, with - standing for the empty prefix. In each frame the cell being filled is marked now, and the cells it reads are marked as compared: the diagonal on a match, the cell above and the cell to the left on a mismatch.

As you watch, notice that the numbers never go down as you move right or down. A longer prefix can only share as much as a shorter one, or more.

Step throughFilling the table for abcde and ace

Rows are prefixes of abcde and columns prefixes of ace, with - for the empty prefix. Each cell is the LCS length of its two prefixes.

  1. -ace-0000a0b0c0d0e0
    rows
    prefixes of abcde
    columns
    prefixes of ace

    1Row 0 and column 0 hold 0, because an empty prefix shares nothing with anything. Every other cell is still blank.

  2. -ace-0000a01b0c0d0e0
    cell
    a vs a
    last letters
    a and a
    rule
    diagonal + 1
    value
    1

    2Cell a vs a: the last letters match, so we take the diagonal cell, 0, and add 1. The prefixes a and a share 1 letter.

  3. -ace-0000a0111b0c0d0e0
    cell
    a vs ace
    last letters
    a and e
    rule
    larger of up and left
    value
    1

    3The rest of row a: a vs ac and a vs ace end in different letters, so each copies the larger of up and left, which is 1.

  4. -ace-0000a0111b0111c0d0e0
    cell
    ab vs ace
    last letters
    b and e
    rule
    larger of up and left
    value
    1

    4Row b has no match at all, since b is not in ace. Every cell copies the larger neighbour, so the row stays at 1.

  5. -ace-0000a0111b0111c012d0e0
    cell
    abc vs ac
    last letters
    c and c
    rule
    diagonal + 1
    value
    2

    5Cell abc vs ac: both end in c, a match. The diagonal cell, ab vs a, holds 1, so this cell becomes 2.

  6. -ace-0000a0111b0111c0122d0e0
    cell
    abc vs ace
    last letters
    c and e
    rule
    larger of up and left
    value
    2

    6Cell abc vs ace: c and e differ. Up holds 1 and left holds 2, so we copy 2. Dropping the e of ace loses nothing.

  7. -ace-0000a0111b0111c0122d0122e0
    cell
    abcd vs ace
    last letters
    d and e
    rule
    larger of up and left
    value
    2

    7Row d has no match, because d is not in ace. Each cell copies its larger neighbour, giving 1, 2, 2.

  8. -ace-0000a0111b0111c0122d0122e012
    cell
    abcde vs ac
    last letters
    e and c
    rule
    larger of up and left
    value
    2

    8In row e, the first two cells differ in their last letters and copy their larger neighbours, 1 and then 2.

  9. -ace-0000a0111b0111c0122d0122e0123
    cell
    abcde vs ace
    last letters
    e and e
    rule
    diagonal + 1
    value
    3

    9The last cell, abcde vs ace, ends in e on both sides. The diagonal holds 2, so this cell is 3, the answer.

Read the frames where a match happens. In the second frame a meets a, and the diagonal 0 becomes 1. In the fifth, abc meets ac, both ending in c, and the diagonal 1, from ab and a, becomes 2. In the last frame abcde meets ace, both ending in e, and the diagonal 2 becomes 3.

Every other cell is a mismatch and copies its larger neighbour. Look at the sixth frame, abc against ace. The letters c and e differ, the cell above holds 1 and the cell to the left holds 2, so the cell takes 2: dropping the e of ace keeps the ac we already matched. Each cell took a constant amount of work, and the bottom right cell, 3, is the answer.

6The complete Java solution

The method makes a table with one extra row and column for the empty prefixes, fills it with the two rules, and returns the bottom right cell. main runs our example, the second example, two strings with nothing in common, an empty string, and repeated letters.

Java
public class LCS {
// dp[i][j] = length of the LCS of the first i chars of a and the first j chars of b.
static int lcs(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1]; // row 0 and column 0 stay 0: empty prefix
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (a.charAt(i - 1) == b.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1; // both last chars join the subsequence
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); // drop one last char
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
System.out.println(lcs("abcde", "ace")); // 3
System.out.println(lcs("ABCBDAB", "BDCABA")); // 4
System.out.println(lcs("abc", "def")); // 0
System.out.println(lcs("", "abc")); // 0
System.out.println(lcs("aaaa", "aa")); // 2
}
}

Let us read lcs in the order it runs. m and n are the lengths. new int[m + 1][n + 1] makes the table, and Java fills it with zeros, so row 0 and column 0 are already correct without a line of code.

The outer loop takes the prefixes of a one letter longer each time, and the inner loop does the same for b, so each cell's three neighbours are filled before it. a.charAt(i - 1) is the last letter of the first i letters; the minus one is there because cell i stands for a prefix of length i, while string positions start at 0. Forgetting this shift is the most common mistake here, and it shows up as an index out of range or a table shifted by one.

On a match the cell takes the diagonal plus one, and otherwise the larger of up and left. When the loops finish, dp[m][n] is the answer for the whole strings.

So main prints 3 for abcde and ace, 4 for ABCBDAB and BDCABA, 0 for abc and def, 0 when one string is empty, and 2 for aaaa and aa, since aa can match only two of the a letters.

7How much it costs, and the cases at the edges

Count on the example first. The loops filled 5 x 3 = 15 cells, each with one comparison and one or two reads. For strings of lengths m and n that is m x n cells, so the time is O(m n). The table holds (m + 1)(n + 1) numbers, so the space is O(m n) as well.

The space can shrink. Each row reads only the row above it, so we can keep just two rows and make the shorter string the columns, giving O(min(m, n)) space. We keep the full table here because it is easier to follow and because it lets us rebuild the subsequence itself.

Comparing the approaches
ApproachTimeExtra space
Plain recursion over both choicesabout O(2^(m + n))O(m + n) call stack
Recursion with memoisationO(m n)O(m n) plus call stack
Table filled bottom upO(m n)O(m n)
Table with two rowsO(m n)O(min(m, n))

The edge cases need no special code. An empty string gives a table of one row or one column of zeros, so the answer is 0. Strings with no common letter never take the match rule, and every cell stays 0. Repeated letters, as in aaaa and aa, are counted correctly, because a match always steps diagonally, using up one letter from each string, so a letter of the shorter string can be matched only once.

8Follow-up questions

How do you return the subsequence itself, not only its length?

We walk back through the table from the bottom right cell. If the last letters of the two prefixes match, that letter is part of the answer, so we write it down and step diagonally up and left. Otherwise we step to whichever neighbour, up or left, holds the larger value, since that is where the cell's value came from. We stop at row 0 or column 0 and reverse the letters we wrote down. For our example the walk collects e, c and a, which reversed gives ace. It takes O(m + n) steps but needs the full table, which is why the two-row version cannot do it.

How is LCS related to edit distance?

Both fill a table over pairs of prefixes using the same three neighbours. Edit distance counts the fewest insertions, deletions and replacements that turn one string into the other, so on a mismatch it takes 1 plus the smallest of the three neighbours instead of the larger of two. If only insertions and deletions are allowed, the edit distance is exactly m + n - 2 x LCS, because every letter outside the common subsequence must be deleted from one string or inserted from the other.

What changes for the longest common substring?

A substring must be one unbroken piece, so a mismatch breaks the run instead of carrying the best value forward. The rule becomes dp[i][j] = dp[i-1][j-1] + 1 on a match and 0 otherwise, and the answer is the largest value anywhere in the table, not the bottom right cell.

9Conclusion

We found the longest common subsequence by giving every pair of prefixes one cell in a table: on matching last letters the cell is the diagonal plus one, and otherwise the larger of the cell above and the cell to the left. That turns a recursion that solves the same pair again and again into one pass over m x n cells, O(m n) time, with O(min(m, n)) space possible using two rows. The clue to remember is a choice at every step plus repeated smaller problems, which means dynamic programming, and two strings mean a table over pairs of prefixes.

What to say in the interviewAbout 90 seconds aloud

Open with

I need the length of the longest sequence of letters that appears in both strings in the same order, not necessarily side by side. For abcde and ace that is ace, length three, and an empty string gives zero.

Then, if they want more

The brute force compares from the front: on a match I take the letter and move both, and on a mismatch I try skipping a letter of either string and keep the better.

That branches twice per mismatch, so it is exponential, but the only state is the pair of positions, and there are just m times n pairs, so the same subproblems repeat. That is the dynamic programming signal.

I define dp of i, j as the LCS length of the first i letters of a and the first j letters of b, with zeros for empty prefixes. If the last letters match, dp of i, j is the diagonal plus one, because taking a match is always safe.

Otherwise it is the larger of the cell above and the cell to the left, since one last letter must be dropped. I fill row by row and return the bottom right cell. That is O(m n) time and space, and since each row only reads the previous one, two rows cut the space to the shorter length. If they want the string itself, I walk back from the corner.

About this answer

Last updated
14 November 2026
Written for
Java 21, using only java.util
Checked
The Java solution was compiled and run, and each printed result matches the comment beside it. The pictures are checked against the format when the site is built. The explanation around the code is a study note: confirm anything critical against the documentation below. What the checks cover
Where the question comes from
Public interview write-ups, reworded by Scrivio; counted 20 times in that collection. How it is counted
Official documentation
java.util, package documentation
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Find the length of the longest common subsequence of two strings using dynamic...": https://scrivio-interview-library.netlify.app/data-structures/solutions/find-the-length-of-the-longest-common-subsequence-of-two-strings-fc69e5/