Longest Common Subsequence
Find the length of the longest sequence of letters that appears, in order, in both strings.
The problem
You get two strings, text1 and text2. A subsequence keeps some letters of a string in their original order, not necessarily next to each other. Return the length of the longest subsequence the two strings have in common, or 0 if they share no letters.
Input text1 = "masala", text2 = "salad"
Output 4
sala appears in both, in order.
Input text1 = "kitchen", text2 = "chicken"
Output 4
chen is one answer: c, h, e and n appear in this order in both words.
Key constraint: Each string has at most 1,000 letters, so a table of about a million cells is fine.
How to spot the pattern
- You compare two sequences letter by letter while keeping their order.
- Matching or dropping the last letter of each string leaves a smaller version of the same problem.
The idea
State: lcs[i][j] is the answer for the first i letters of text1 and the first j letters of text2. If those two last letters match, both can join the common subsequence, so lcs[i][j] = lcs[i - 1][j - 1] + 1. If they differ, at least one of them is not used, so lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]).
Brute force: List all 2^m subsequences of one string and check each against the other, which takes O(2^m * n) time.
Step by step
- 1Make a table
lcsof size(m + 1) x (n + 1)filled with 0; row 0 and column 0 stand for an empty prefix. - 2Fill it row by row, for
ifrom 1 tomandjfrom 1 ton. - 3If
text1[i - 1] == text2[j - 1], setlcs[i][j] = lcs[i - 1][j - 1] + 1. - 4Otherwise set
lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]). - 5Return
lcs[m][n].
See the pattern move
The 2d dynamic programming pattern on a small example. Step through it, or press play.
Code
class Solution:
def longestCommonSubsequence(self, text1: str, text2: str) -> int:
m, n = len(text1), len(text2)
# lcs[i][j] = LCS length of the first i letters of text1 and the first j letters of text2
lcs = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if text1[i - 1] == text2[j - 1]:
lcs[i][j] = lcs[i - 1][j - 1] + 1 # both last letters join the subsequence
else:
lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1]) # drop one of the last letters
return lcs[m][n]Complexity
Time
O(m * n)
Space
O(m * n)
One table cell per pair of prefixes, each filled in O(1).
Watch out for
- Mixing up subsequence and substring: the common letters don't have to sit next to each other.
- Off-by-one indexing:
lcs[i][j]covers the firstiletters, so it comparestext1[i - 1]withtext2[j - 1].
Follow-up questions
Can you cut the memory?
Each row only uses the row above it, so two rows are enough. Index the rows by the shorter string to get O(min(m, n)) space.
How would you print the subsequence itself?
Walk back from lcs[m][n]: on a match take the letter and move diagonally, otherwise move toward the larger neighbor. Reverse the letters you collected.
In Hinglish
Dono strings ke aakhri letter same hain toh dono le lo aur diagonal se +1 karo. Alag hain toh ek letter chhodo, upar ya left mein jo bada ho wahi lo.