DSA
    advanced

    Longest Common Subsequence (LCS)

    Longest Common Subsequence (LCS)

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

    ⏱ O(mn)
    💾 O(mn)
    Playing
    ØACE
    Ø0000
    A00
    1,1
    00
    B0000
    C0000
    D0000
    E0000

    Scroll horizontally to see the full table

    String 1
    String 2

    Comparing s1[0] ('A') with s2[0] ('A')

    500%
    Live Variables
    char1A
    char2A

    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