Longest Common Subsequence
Find the longest string of letters two words share in the same order
DSA, Medium, 2-D DP
Which structure or algorithm, and what does it cost.
You get two strings, first and second. A common subsequence is a string you can make from each of them by deleting some letters, maybe none, while keeping the order of the rest. The kept letters need not be next to each other. Return the length of the longest common subsequence. Return 0 if the strings share no such letters.
Examples
Constraints
- 0 <= length of
first,second<= 2,000. - Both strings use lowercase English letters.
Your answer must contain
- The simple method and why it is too slow; the better method; the best method and why it is correct; code; time and memory cost; a hand trace of example 1.
Target Aim for O(n * m) time and O(m) memory, where n and m are the two lengths.
Hints
Try the problem first. Open one hint at a time.
Hint 1 a nudge
Compare only the last letters of the two words. What can you say when they are equal, and when they differ?
Hint 2 the approach
Define the answer for every pair of prefixes: the first i letters of one word and the first j letters of the other. Longer pairs use shorter ones.
Hint 3 the key step
If the newest letters match, add 1 to the answer without both of them. If not, take the larger answer after dropping one. Fill a table row by row.
Walkthrough
Full walkthrough brute force to best
Brute force
Write down every subsequence of first, which is 2^n of them, and test each against second. Keep the longest that fits. This takes about 2^n * m steps, so it works only for words of about 20 letters.
Better method
Recursion with memory. Let L(i, j) be the answer for the first i letters of first and the first j letters of second. If the last letters match, L(i, j) is L(i - 1, j - 1) + 1. Otherwise it is the larger of L(i - 1, j) and L(i, j - 1). Store each pair. There are n * m pairs, so this is O(n * m) time and memory. The recursion can go n + m deep.
Best method
Fill the same rule as a table, from the small prefixes up. Cell (i, j) holds the answer for the first i letters of first and the first j letters of second. Row 0 and column 0 are 0, because an empty word shares nothing. If the two newest letters match, pairing them is never worse than leaving either one out, so the cell is the diagonal cell plus 1. If they differ, at least one of them is unused, so the cell is the larger of the cell above and the cell to the left. Each row needs only the row before it, so keep two lists. The answer is the last cell.
Hand trace
Run on first = "bread", second = "bear". Columns are the prefixes "", b, be, bea, bear. The first row is [0, 0, 0, 0, 0]. After b: [0, 1, 1, 1, 1]. After r: [0, 1, 1, 1, 2]. After e: [0, 1, 2, 2, 2]. After a: [0, 1, 2, 3, 3]. After d: [0, 1, 2, 3, 3]. The last value is 3.
Code
def common_length(first, second):
prev = [0] * (len(second) + 1) # prev[j]: answer for the earlier rows of first and second[:j]
for a in first:
cur = [0]
for j, b in enumerate(second):
cur.append(prev[j] + 1 if a == b else max(prev[j + 1], cur[j]))
prev = cur
return prev[-1]Time and memory
O(n * m) time, one step per cell. O(m) memory for two rows, where m is the length of second.
Common mistakes
- Looking for a common substring. The letters need not be adjacent: in example 1 the letters b, e and a skip the r.
- On a match, adding 1 to the larger of the cell above and the cell to the left instead of the diagonal. One letter is then paired twice: first = "aa", second = "a" gives 2, not 1.
- Leaving out the empty prefix, so the first letters have no row 0 or column 0 to read from.