Longest Common Subsequence
LeetCode 1143 · Medium · solution, intuition & step-by-step walkthrough
lcs(i, j) = 1 + lcs(i+1, j+1) on a match, else max(lcs(i+1, j), lcs(i, j+1)).
This is how I solved Longest Common Subsequence (LeetCode 1143), a medium problem from the LCS pattern. Below: the intuition, the approach step by step, my accepted Python code and the 3 versions I wrote on the way, animated test cases and a line-by-line debugger.
Intuition
Compare the current characters of both strings. If they match, they can both be part of the subsequence: take 1 and move both pointers. If not, one of them is not in the answer — drop it from one side or the other and keep the better result.
Approach
- 1
Top-down lcs(i, j) with lru_cache; either string exhausted → 0.
- 2
Bottom-up: fill dp from the end of both strings back to (0, 0).
- 3
Each row only needs the row below it, so the final version keeps prev and cur arrays.
How I solved it · from first idea to final
lru_cache lcs(i, j).
2-D table from the end.
prev / cur rolling rows.
Recursion + memoPythonO(m·n) time · O(m·n) space
from functools import lru_cache
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
#case 1:
#letters are correct index are same
#1+lcs(i+1,j+1)
#case 2
#letters at current index are not same
#max(lcs(i+1,j),lcs(i,j+1))
#base case if any of the string is out of index return 0
@lru_cache(maxsize=None)
def lcs(i,j):
if i==len(text1) or j == len(text2):
return 0
if text1[i]==text2[j]:
return 1+lcs(i+1,j+1)
else:
return max(lcs(i+1,j),lcs(i,j+1))
return lcs(0,0)TabulationPythonO(m·n) time · O(m·n) space
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
#case 1:
#letters are correct index are same
#1+lcs(i+1,j+1)
#case 2
#letters at current index are not same
#max(lcs(i+1,j),lcs(i,j+1))
#base case if any of the string is out of index return 0
m = len(text1)
n = len(text2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
if text1[i]==text2[j]:
dp[i][j]=1+dp[i+1][j+1]
else:
dp[i][j]=max(dp[i+1][j],dp[i][j+1])
return dp[0][0]Space-optimised rowsPythonO(m·n) time · O(n) space
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
#case 1:
#letters are correct index are same
#1+lcs(i+1,j+1)
#case 2
#letters at current index are not same
#max(lcs(i+1,j),lcs(i,j+1))
#base case if any of the string is out of index return 0
m = len(text1)
n = len(text2)
prev = [0]*(n+1)
cur = [0]*(n+1)
for i in range(m-1,-1,-1):
for j in range(n-1,-1,-1):
if text1[i]==text2[j]:
cur[j]=1+prev[j+1]
else:
cur[j]=max(prev[j],cur[j+1])
prev=cur[:]
return prev[0]Longest Common Subsequence — FAQ
What is the intuition behind Longest Common Subsequence?
Compare the current characters of both strings. If they match, they can both be part of the subsequence: take 1 and move both pointers. If not, one of them is not in the answer — drop it from one side or the other and keep the better result.
How do you solve Longest Common Subsequence (LeetCode 1143)?
1. Top-down lcs(i, j) with lru_cache; either string exhausted → 0. 2. Bottom-up: fill dp from the end of both strings back to (0, 0). 3. Each row only needs the row below it, so the final version keeps prev and cur arrays.
What is the time and space complexity of Longest Common Subsequence?
Time: O(m · n). Space: O(n) in the final version. (Accepted approach: Space-optimised rows.)
What are common mistakes in Longest Common Subsequence?
Subsequence ≠ substring — characters don't have to be contiguous. Copy cur into prev each row (prev = cur[:]).
Is there more than one way to solve Longest Common Subsequence?
Recursion + memo (O(m·n) time · O(m·n) space): lru_cache lcs(i, j). Tabulation (O(m·n) time · O(m·n) space): 2-D table from the end. Space-optimised rows (O(m·n) time · O(n) space): prev / cur rolling rows.