AdvancedAbout 25 min

    Longest Common Subsequence (LCS)

    Read the full article on Substack

    8 min read.

    Finds the longest subsequence present in both sequences (not necessarily contiguous).

    Think of it this way: Think of comparing two DNA sequences. You want to find the longest strand of matching genetic code that appears in the same order in both, even if there are 'junk' genes in between.

    εBDCABAεABCBDAB00000000000000

    Compare "ABCBDAB" with "BDCABA". The first row and column are 0 (an empty string shares nothing).

    1/52

    Check your understanding

    Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.

    The LCS recurrence

    Schematic

    Fill in what each case of the LCS table stores.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    Compare a[i] with b[j]

    if they match
    if they differ
    row 0 or column 0
    3 pieces left to place

    Quiz

    20 questions
    Question 1 of 20
    Score: 0

    If characters match at dp[i][j], where does the value come from?

    Done with this lesson?

    Sign in free to keep your progress, streak and quiz scores.

    Keep going