Longest Common Subsequence (LeetCode 1143): Solution and Explanation
Given two strings, return the length of the longest sequence of characters that appears in both, in the same relative order but not necessarily next to each other. If they share no characters, the answer is 0.
Watch it run step by step
Try your own input and write the code →Intuition
The brute force lists every subsequence of the first string, of which there are 2^n, and checks whether each one also appears in the second string. That is exponential and hopeless for strings of length 1,000. It does hint at the structure, though: the problem is about making a choice at each character.
Think about the first characters of the two remaining suffixes, text1[i] and text2[j]. If they are equal, it is always safe to use that character as part of the common subsequence and move both pointers forward, giving 1 plus the answer for i + 1, j + 1. If they differ, at least one of them cannot be the start of the common subsequence, so you try skipping text1[i] or skipping text2[j] and keep the better result.
Every subproblem is described by just two indices, so there are only (n + 1) × (m + 1) of them. Store dp[i][j] as the LCS length of text1[i:] and text2[j:]. The extra row and column of zeros at the end represent empty suffixes, which share nothing. Filling the table from the bottom-right corner backward means each cell's three dependencies, right, down and diagonal, are already filled when you need them, and the answer ends up in dp[0][0].
Approach: Bottom-up 2D DP over suffixes
- Create a table
dpwithlen(text1) + 1rows andlen(text2) + 1columns, all zeros. - Loop
ifrom the last index oftext1down to 0, and inside itjfrom the last index oftext2down to 0. - If
text1[i] == text2[j], setdp[i][j] = 1 + dp[i + 1][j + 1]to use the matching character. - Otherwise set
dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]), skipping one character from either string. - Return
dp[0][0], the LCS of the two full strings.
Step-by-step example
text1 = "abcde", text2 = "ace"
- Row i = 4 ('e'): it matches text2's 'e' at j = 2, so
dp[4][2] = 1. The cells for 'c' and 'a' inherit 1 from the right, giving row [1,1,1]. - Row i = 3 ('d'): no matches, so each cell takes the max of right and down, giving row [1,1,1].
- Row i = 2 ('c'): at j = 1 it matches 'c', so
dp[2][1] = 1 + dp[3][2] = 2. Thendp[2][0] = max(2, 1) = 2, giving row [2,2,1]. - Row i = 1 ('b'): no matches, giving row [2,2,1].
- Row i = 0 ('a'): at j = 0 it matches 'a', so
dp[0][0] = 1 + dp[1][1] = 3. - Return 3, corresponding to the subsequence "ace".
Code: Python, Java, C++
1class Solution:
2 def longestCommonSubsequence(self, text1: str, text2: str) -> int:
3 dp = [[0 for j in range(len(text2) + 1)] for i in range(len(text1) + 1)]
4
5 for i in range(len(text1) - 1, -1, -1):
6 for j in range(len(text2) - 1, -1, -1):
7 if text1[i] == text2[j]:
8 dp[i][j] = 1 + dp[i + 1][j + 1]
9 else:
10 dp[i][j] = max(dp[i][j + 1], dp[i + 1][j])
11
12 return dp[0][0]1class Solution {
2 public int longestCommonSubsequence(String text1, String text2) {
3 int[][] dp = new int[text1.length() + 1][text2.length() + 1];
4
5 for (int i = text1.length() - 1; i >= 0; i--) {
6 for (int j = text2.length() - 1; j >= 0; j--) {
7 if (text1.charAt(i) == text2.charAt(j)) {
8 dp[i][j] = 1 + dp[i + 1][j + 1];
9 } else {
10 dp[i][j] = Math.max(dp[i][j + 1], dp[i + 1][j]);
11 }
12 }
13 }
14 return dp[0][0];
15 }
16}1class Solution {
2public:
3 int longestCommonSubsequence(string text1, string text2) {
4 vector<vector<int>> dp(text1.size() + 1, vector<int>(text2.size() + 1, 0));
5
6 for (int i = text1.size() - 1; i >= 0; i--) {
7 for (int j = text2.size() - 1; j >= 0; j--) {
8 if (text1[i] == text2[j]) {
9 dp[i][j] = 1 + dp[i + 1][j + 1];
10 } else {
11 dp[i][j] = max(dp[i][j + 1], dp[i + 1][j]);
12 }
13 }
14 }
15 return dp[0][0];
16 }
17};Time and space complexity
O(n × m)
Each of the n × m cells is computed once in constant time, where n and m are the lengths of the two strings.
O(n × m)
The full (n + 1) × (m + 1) table is stored. Since each row only reads the row below it, two rows are enough to bring this down to O(min(n, m)).
Other approaches
Two-row DP (time O(n × m), space O(min(n, m)))
Keep only the current row and the row below, swapping them after each i. It gives the same answer with much less memory, though you lose the full table needed to reconstruct the actual subsequence.
Top-down recursion with memoization (time O(n × m), space O(n × m))
Write lcs(i, j) with the same match and skip cases and cache results in a dictionary or 2D array. It is often how people first derive the recurrence, but recursion depth can reach n + m.
Common mistakes
- Sizing the table as n × m instead of (n + 1) × (m + 1), which leaves no room for the empty-suffix base cases and causes index errors.
- Adding 1 to
max(dp[i][j + 1], dp[i + 1][j])on a match instead of using the diagonaldp[i + 1][j + 1], which can count the same character twice. - Confusing subsequence with substring. A common substring must be contiguous and uses a different recurrence that resets to 0 on a mismatch.
- Building the table with
[[0] * (m + 1)] * (n + 1)in Python, which makes every row the same list object.
Frequently asked questions
What is the time complexity of longest common subsequence?
It is O(n × m), since there is one subproblem per pair of indices and each is solved in constant time. With two rows of storage the space can drop to O(min(n, m)).
How do I print the actual longest common subsequence?
Keep the full table, then start at (0, 0). When the characters match, output that character and move diagonally. Otherwise move toward whichever neighbor, right or down, holds the larger value.
What is the difference between longest common subsequence and longest common substring?
A subsequence can skip characters while a substring must be contiguous. For substring, a mismatch resets the cell to 0 and the answer is the maximum cell anywhere in the table, not the corner.
Why is it safe to take a matching character greedily?
If both suffixes start with the same character, any common subsequence that does not use it can be modified to use it without becoming shorter. So taking the match never loses the optimum.