Abstract flowing gradient in deep indigo and blue tones, smooth and luminous, evoking a modern digital learning atmosphere

Computer Science and programming articles. We do not sell courses.

Solving the Longest Common Subsequence with Dynamic Programming

Two sequences rarely line up exactly, and that mismatch is where the longest common subsequence problem earns its keep. Given two strings, lists of events, or logs, the task is to find the longest run of elements appearing in both inputs while preserving their relative order. The matched elements need not sit next to each other; they can be scattered across each input. That single relaxation turns a brute-force search into a problem with a clean and efficient solution through dynamic programming.

The classic illustration uses the strings AGGTAB and GXTXAYB. Their longest common subsequence is GTAB, a length of four, and every character of that answer appears in both strings in the correct order even though the surrounding characters differ entirely. This is subtly different from the longest common substring, where every matched character must form one unbroken block, and different again from a set intersection, which throws ordering away. Getting those distinctions straight saves a surprising amount of wasted effort.

Dynamic programming suits the problem because the answer for one pair of prefixes depends only on smaller, overlapping subproblems. Once the recurrence is written down, the same logic serves a pair of short strings typed into a REPL and a multi-megabyte diff running inside a CI pipeline. The implementation language barely matters; what matters is the fill order of the grid and how much memory you choose to keep while filling it.

The walkthrough below starts with what the problem actually measures, then derives the recurrence, adds memoisation, and moves to a bottom-up tabulation with rolling rows for long inputs. It also covers tracing the answer back so you can print the subsequence itself rather than only its length, and it places the technique alongside edit distance, the diff algorithm, and tree-based models so you can pick the right tool for the job. Examples lean on Australian datasets and workplaces, since the site serves readers from Melbourne, Canberra, Adelaide, and everywhere else along the coast.

What the longest common subsequence actually measures

Formally, a subsequence of a sequence is any list obtained by deleting zero or more elements without reordering what remains. The longest common subsequence, or LCS, is therefore the longest list that is a subsequence of both inputs at once. Order is the defining constraint: a candidate match must respect the left-to-right positions of the original sequences, and gaps are allowed on either side.

Take ABCBDAB and BDCABA. The answer has length four, and BCBA is one valid result, as is BDAB. Both can be traced through the inputs while skipping elements, which already hints at something important: when several answers share the maximum length, the algorithm may return any of them, and tie-breaking rules become a design decision rather than an accident.

Real workloads are full of sequences that only partially overlap. Version control systems compare committed snapshots, plagiarism checkers compare student submissions against a corpus, and file synchronisation tools compare divergent copies of a document. Australian product teams, from Atlassian's Sydney offices through to Canberra's government service designers, watch diff views scroll past every day of the working week.

How the recurrence becomes memoised code

Write L(i, j) for the length of the longest common subsequence between the first i characters of string A and the first j characters of string B. When either prefix is empty the answer is zero, because an empty string shares nothing with a non-empty one. When the final characters match, that pair contributes one point and you extend the best answer for the two shorter prefixes. When they differ, you take the better of dropping the last character of A or the last character of B.

L(i, j) = 0                                if i = 0 or j = 0
L(i, j) = 1 + L(i - 1, j - 1)               if A[i - 1] = B[j - 1]
L(i, j) = max(L(i - 1, j), L(i, j - 1))      otherwise

Implemented literally as recursion, this explores an exponential tree of possibilities, because each mismatch branches into two overlapping subproblems that get recomputed from scratch. Caching results by the pair of indices collapses the work, since every state is then solved once.

def lcs_length(a, b):
    memo = {}

    def solve(i, j):
        if i == 0 or j == 0:
            return 0
        if (i, j) in memo:
            return memo[(i, j)]
        if a[i - 1] == b[j - 1]:
            result = 1 + solve(i - 1, j - 1)
        else:
            result = max(solve(i - 1, j), solve(i, j - 1))
        memo[(i, j)] = result
        return result

    return solve(len(a), len(b))

The main strategies differ mainly in how often they revisit a state and how much memory they hold while working.

Approach Time Extra space Practical notes
Naive recursion O(2^(m+n)) worst case Call stack only Fine for teaching, collapses on real inputs
Memoised recursion O(m·n) O(m·n) plus stack Easiest to read, but recursion depth bites
Bottom-up matrix O(m·n) O(m·n) Predictable, no recursion ceiling
Rolling rows O(m·n) O(min(m, n)) Best for long strings, loses traceback data

Memoisation reads beautifully in Python, though the interpreter's recursion limit will stop a long pair of strings dead in their tracks. Converting the same logic into an explicit loop removes that ceiling entirely, which is exactly what the tabulated version does.

Tabulating the answer bottom-up

The bottom-up version stores the same L values in a grid, filling it row by row so that every dependency has already been computed. The match case reads the diagonal cell, and the mismatch case reads the cell above and the cell to the left.

def lcs_length_dp(a, b):
    rows, cols = len(a), len(b)
    dp = [[0] * (cols + 1) for _ in range(rows + 1)]

    for i in range(1, rows + 1):
        for j in range(1, cols + 1):
            if a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])

    return dp[rows][cols]

Since row i depends only on row i - 1 and on its own previous column, two rows are enough. Keeping the shorter string on the columns shrinks memory to O(min(m, n)), which matters when one input runs to hundreds of thousands of symbols and the other to a dozen. Readers who prefer working closer to the metal can port the same recurrence directly, and the C programming guide on this site covers the pointer and array habits that make a manual grid comfortable to work with.

For very large inputs, the quadratic time cost becomes the limiting factor rather than memory. Hunt–Szymanski style matching and bit-parallel formulations improve on the plain grid when strings share few symbols, and they are worth reaching for only once profiling shows the simple version is genuinely too slow.

Recovering the subsequence itself

A length is often not what the caller wants. To recover the actual matched elements, walk backwards from the bottom-right corner of the grid: if the two characters match, record them and step diagonally; otherwise step up or left towards whichever neighbour carries the larger value. Storing the direction taken at each cell during the forward pass makes the walk a simple lookup, at the cost of one extra byte per cell.

Ties need a rule. When dp[i - 1][j] equals dp[i][j - 1], either direction is defensible, and the choice decides which of several equally long answers you see. Comparing ABCBDAB with BDCABA might return BCBA or BDAB depending on that rule, and both are correct.

Sequences of symbols show up in unexpected corners of Australian industry. Form guides list a horse's recent runs as a short string of placings, and analysts compare two such strings to find the longest shared stretch of results, which is exactly this alignment logic applied to a tiny alphabet. The horse racing betting Australia review describes the betting market around those guides and the data pipelines behind them, where sequence comparisons of this kind quietly support handicapping models and price moves. As an Australian developer will tell you after an arvo of debugging, the fill order is usually the culprit, and once it is right the rest is no worries.

Choosing between LCS and its neighbours

Longest common subsequence belongs to a family of comparison problems, and each member answers a different question. Longest common substring demands contiguity and suits things like finding repeated blocks in a log. Levenshtein distance counts insertions, deletions, and substitutions, which matches how a spell checker or a fuzzy name matcher thinks about errors. The Myers diff algorithm finds a minimal edit script between two files, which is why it powers the line-by-line diff views developers stare at during code review.

The choice follows the shape of the question rather than any ranking of methods. Ask whether order matters and whether gaps are permitted, and you land on LCS. Ask how many single-character edits would transform one string into the other, and edit distance is the right instrument. Ask which lines changed in a file, and diff is the tool, especially once you want the output formatted for human eyes.

Tree-based machine learning takes a completely different route. A model such as a CART decision tree splits data on a feature value to predict an outcome, whereas the LCS grid fills cell by cell to measure similarity between two fixed sequences; one learns structure from labelled examples, the other counts matches combinatorially. The CART decision tree guide walks through how those splits are chosen, and it is a useful contrast when you are deciding whether a problem wants prediction or comparison.

Mastering this single recurrence pays off well beyond the interview question. The same table-filling intuition behind memoisation, tabulation, and rolling arrays appears in sequence alignment for genomics, in aligning speech transcripts, and in every pipeline that must decide how closely two histories resemble one another. Once the recurrence sits comfortably in your head, the language, the data structure, and the input size become ordinary engineering choices rather than obstacles.