Quick revision
The short answer
The table rule is dp[i][j] = dp[i-1][j-1] + 1 when the characters match, else max(dp[i-1][j], dp[i][j-1]). Each row only reads the row above, so we keep two int arrays sized by the shorter string, which gives O(m x n) time and O(min(m, n)) memory. Rebuilding the subsequence itself needs either the full table, O(m x n) memory, or Hirschberg's divide and conquer algorithm, which keeps memory linear.
What to remember
In this answer, we used the recurrence dp[i][j] = dp[i-1][j-1] + 1 on a match and max(dp[i-1][j], dp[i][j-1]) otherwise, and noticed that each row only reads the previous one, so two arrays sized by the shorter string give O(min(m, n)) memory with O(m x n) time. Reconstructing the subsequence needs the full table for the simple walk back, or Hirschberg's divide and conquer to keep memory linear. We also saw that diff tools build on these ideas with Myers' algorithm, and that copying strings to char arrays keeps the inner loop lean.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The table rule is dp[i][j] = dp[i-1][j-1] + 1 when the characters match, else max(dp[i-1][j], dp[i][j-1]). Each row only reads the row above, so we keep two int arrays sized by the shorter string, which gives O(m x n) time and O(min(m, n)) memory. Rebuilding the subsequence itself needs either the full table, O(m x n) memory, or Hirschberg's divide and conquer algorithm, which keeps memory linear.
Why this question is asked
The longest common subsequence, LCS, is the longest sequence of characters that appears in both strings in the same order, not necessarily next to each other. It is the idea behind diff tools, version control merges and DNA alignment, so it is worth understanding beyond the interview. Interviewers ask for the reduced memory version because it shows whether we can look at a DP table and see which cells a step actually needs. In this answer, we will recap the full table, reduce it to two rows, make sure we size by the shorter string, explain how reconstruction works and why it needs more memory, and finish with how real diff tools use these ideas.
1A Quick Recap of the LCS Table
For strings a of length m and b of length n, let dp[i][j] be the LCS length of the first i characters of a and the first j characters of b. If either prefix is empty, the LCS is 0, so row 0 and column 0 are zeros. For the other cells there are two cases. If a[i-1] equals b[j-1], that character can end a common subsequence, so dp[i][j] = dp[i-1][j-1] + 1. If not, one of the two characters is not part of the LCS, so we take the better of dropping it from a or from b: max(dp[i-1][j], dp[i][j-1]).
For a = "ABCBDAB" and b = "BDCABA", the final cell dp[7][6] is 4, and one LCS is "BCBA". Filling the table takes m x n steps, and storing it takes m x n ints, 4 bytes each. For two 20,000-character strings that is 400 million cells, about 1.6 GB, which is why the memory question matters.
2Keeping Only Two Rows
Look at which cells a step reads: the cell above, the cell to the left, and the cell diagonally above-left. All of them are in the current row or the previous row. So once row i is finished, row i - 1 is never read again, and we can keep just two arrays, prev and curr, and swap them after each row.
4 messages in order. Play them, or step through them one at a time.
Only the previous row and the current row are ever read.
Notice two details. First, after the swap the old prev array becomes curr, still holding old values, but every curr[j] for j from 1 is overwritten before it is read, and curr[0] stays 0, so we never need to clear it. Second, we swap the strings at the start so the arrays are sized by the shorter one. The time is still O(m x n), but the memory is O(min(m, n)), which is what the question asked for.
3Why toCharArray Instead of charAt
In a loop that runs hundreds of millions of times, small costs add up. String.charAt checks bounds on every call and, since compact strings in Java 9, has to check whether the string is stored as Latin-1 bytes or UTF-16. The JIT usually inlines and optimises much of this, but copying both strings into char arrays once, as above, gives the inner loop plain array accesses that are easy to optimise. The copy costs O(m + n), which is negligible next to O(m x n). This is the kind of micro-optimisation worth measuring with JMH rather than assuming, but for a tight DP loop it is a sensible default.
4Reconstructing the Subsequence
With the full table, reconstruction is a walk back from dp[m][n]. If the characters at i - 1 and j - 1 match, that character is part of the LCS, so we add it and move diagonally. Otherwise we move toward the larger of the cell above and the cell to the left. We stop when i or j reaches 0 and reverse what we collected.
But there is a catch: the walk back needs the whole table, because it visits cells from every row. With only two rows, the information about where the path went is gone. So reconstruction with this simple method costs O(m x n) memory again.
5Hirschberg's Algorithm Keeps Memory Linear
Hirschberg's algorithm reconstructs the LCS in linear space by divide and conquer. It splits a in half at row m/2. Using the two-row method, it computes the LCS lengths of the first half of a against every prefix of b, and, running the same method on reversed strings, the lengths of the second half of a against every suffix of b. The best split point k of b is where the sum of the two values is largest. The LCS is then the LCS of the first half of a with b[0..k] followed by the LCS of the second half with b[k..n], each solved recursively.
Each level of recursion does a total of about m x n work divided across its pieces, and the levels halve, so the total time is still O(m x n), about twice the simple version, while memory stays O(min(m, n)) plus the recursion stack of O(log m) levels.
- Split a at the middle rowa1 = first half, a2 = second half
- Forward LCS lengths of a1 vs prefixes of btwo-row method
- Backward LCS lengths of a2 vs suffixes of bon reversed strings
- Pick split k maximising the sum
- Recurse on (a1, b[0..k]) and (a2, b[k..n])concatenate the results
- Base case: one character of acheck if it occurs in b
6 steps in order. Play them, or step through them one at a time.
6How Diff Tools Use These Ideas
A line-based diff is an LCS problem where the elements are lines instead of characters: the lines in the LCS are unchanged, and everything else is an insertion or a deletion. Real tools rarely run the plain O(m x n) table, because files with thousands of lines would be slow. Git and GNU diff use Myers' algorithm, which finds a shortest edit script in O((m + n) x D) time, where D is the number of differences, so similar files are compared very quickly, and it has a linear-space variant built on the same middle-split idea as Hirschberg. Java libraries such as java-diff-utils implement Myers' algorithm.
7Follow-up questions
Why can we not use one array instead of two?
We can, with care. The diagonal value prev[j-1] is overwritten when we compute curr[j-1] in the same array, so we keep it in a temporary variable before overwriting each cell. That halves the memory again, at the cost of slightly trickier code.
What is the difference between longest common subsequence and longest common substring?
A substring must be contiguous. For the substring problem, dp[i][j] is the length of the common suffix ending at i and j: dp[i-1][j-1] + 1 on a match and 0 otherwise, and the answer is the maximum cell anywhere in the table, not the last cell.
How does LCS relate to edit distance?
If only insertions and deletions are allowed, the edit distance is m + n - 2 x LCS. Levenshtein distance also allows substitutions and has its own similar recurrence over the same table shape.
8Conclusion
In this answer, we used the recurrence dp[i][j] = dp[i-1][j-1] + 1 on a match and max(dp[i-1][j], dp[i][j-1]) otherwise, and noticed that each row only reads the previous one, so two arrays sized by the shorter string give O(min(m, n)) memory with O(m x n) time. Reconstructing the subsequence needs the full table for the simple walk back, or Hirschberg's divide and conquer to keep memory linear. We also saw that diff tools build on these ideas with Myers' algorithm, and that copying strings to char arrays keeps the inner loop lean.
Open with
The LCS table has dp of i, j as the LCS length of the first i characters of a and the first j of b. If the characters match, it is the diagonal cell plus one; otherwise it is the maximum of the cell above and the cell to the left.
Then, if they want more
Row zero and column zero are zeros. The key observation for memory is that each cell only reads from the current row and the previous row, so I keep two int arrays, prev and curr, compute curr from prev, and swap after every row.
I swap the strings first so the arrays are sized by the shorter one, which gives O(min of m and n) memory with O(m times n) time. I also copy the strings to char arrays once, so the inner loop does plain array reads instead of charAt calls. Reconstruction is the catch.
The usual method walks back from the bottom-right cell, taking the diagonal on a match and otherwise moving toward the larger neighbour, and that needs the whole table, so it is O(m times n) memory.
To reconstruct in linear space I would use Hirschberg's algorithm: split the first string in half, compute forward lengths for the first half and backward lengths for the second half, choose the split point in the second string that maximises their sum, and recurse on both halves. It is about twice the time and linear memory.
Real diff tools use Myers' algorithm, which is built on the same ideas but runs faster when the inputs are similar.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 9
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
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 "Write the longest common subsequence length of two strings in Java with O(min(m, n))...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/6313ff4898/