DSA
    advanced

    Longest Common Subsequence (LCS)

    Software Engineer path · lesson 36 of 99
    time O(mn)
    space O(mn)
    Try:
    Try:
    εBDCABAεABCBDAB00000000000000
    FillingReadMatched char (in LCS)Traceback path

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

    Code (running line highlighted)
    1. 1dp[0][*] = dp[*][0] = 0
    2. 2for i in 1..len(a), for j in 1..len(b):
    3. 3 if a[i-1] == b[j-1]: dp[i][j] = dp[i-1][j-1] + 1 # match: diagonal
    4. 4 else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) # drop one char
    5. 5walk back from dp[m][n] to read the subsequence
    Cells filled
    0 / 42
    Matches
    0 / 12
    Invariant: dp[i][j] = LCS length of a[0..i) and b[0..j).

    LCS so far: …

    Tap any element in the diagram to inspect its state at this step.

    1 / 52

    Keys: ← → step, Space play/pause. Predict mode pauses before key steps and asks what happens next.

    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

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

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

    The short version

    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.

    In more depth

    String Alignment

    LCS is the mother of all "String Comparison" DP problems. It aligns two strings to find the maximum matching characters while keeping their relative order.

    2D Grid Intuition:

    We compare char A[i] and B[j]:

    Match: 1 + result from diagonal (i-1, j-1)
    Mismatch: Take the best outcome from either skipping char A (up) or skipping char B (left).

    This logic underpins 'diff' tools in Git!

    When to reach for this

    • Compare two strings to find similarities/differences
    • Edit distance / Mutation distance
    • Longest Palindromic Sequence (LCS of string and its reverse)

    Interview Questions

    Netflix
    LinkedIn
    Microsoft
    Facebook
    Google
    LinkedIn
    Airbnb
    Facebook
    Microsoft
    Netflix
    Bloomberg

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required