Lesson 2 · Unit 03
Longest common subsequence
Compare two strings prefix by prefix in a table
What you practise
- Reading and filling the table
Try a question from this lesson
Pick one
A subsequence keeps some letters of a string in their original order and skips the rest. Which of these is a subsequence of "CARTON"?
Correct answer
CAT
Why
C, A and T appear in that order in CARTON, with R skipped. The others use the right letters in the wrong order: in TAR the T comes first, in CORN the O comes before the R, and in CANT the N comes before the T.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
One cell, two cases
Let dp[i][j] be the LCS length of the first i letters of one string and the first j letters of the other.
Look at the last letter of each prefix. Same letter: pair them up and add 1 to the diagonal cell, where both prefixes are one shorter. Different: one of the two letters is useless here, so take the better of the cell above and the cell to the left.
def cell(same, diag, up, left):
if same:
return diag + 1
return max(up, left)function cell(same, diag, up, left) {
if (same) return diag + 1;
return Math.max(up, left);
}function cell(
same: boolean,
diag: number,
up: number,
left: number,
): number {
if (same) return diag + 1;
return Math.max(up, left);
}Python notesame would be the result of a comparison such as a[i - 1] == b[j - 1], which is already a bool.
TypeScript noteThe four parameters are listed one per line only to fit the screen. same: boolean is the result of comparing the two letters.
10 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× fill the blanks
- 2× true or false
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.