Skip to lesson content
navan✳THE BUILD LABDSA
0/66 complete
BUILD LAB / DSA/ Dynamic programming
EXPERIMENT 60 / 66

Keep the order, skip the gaps.

Build and reconstruct a shared sequence without requiring contiguous characters.

BY NAVAN SAMI◷ 9 MIN READSTRETCHALGORITHM

01 Model the idea

A subsequence preserves order but may skip positions. The longest common subsequence problem asks for the longest sequence shared by two inputs. If the final characters match, extend the best answer for the two shorter prefixes. Otherwise choose the better result from dropping one final character. A two-dimensional prefix table makes those dependencies explicit.

THE THING THAT MUST STAY TRUE

Each cell stores the optimal length for exactly its pair of prefixes.

02 State the strategy

Read the steps independently of syntax. Explain what each step preserves before translating it into code.

the_strategy.txt
FILL prefix-pair states
MATCH: extend the diagonal answer
MISMATCH: keep the better shortened-prefix answer
BACKTRACK an optimal sequence

03 Make it concrete

The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.

longest_common_subsequence.py
def lcs(a, b):
    table = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(1, len(a) + 1):
        for j in range(1, len(b) + 1):
            table[i][j] = table[i-1][j-1] + 1 if a[i-1] == b[j-1] else max(table[i-1][j], table[i][j-1])
    i, j, result = len(a), len(b), []
    while i and j:
        if a[i-1] == b[j-1]: result.append(a[i-1]); i -= 1; j -= 1
        elif table[i-1][j] >= table[i][j-1]: i -= 1
        else: j -= 1
    return "".join(reversed(result))
print(lcs("CODE", "CONE"))
↳ EXPECTED OUTPUT
COE
  1. 1

    The zero row and column represent empty prefixes. Every interior cell depends only on earlier cells.

  2. 2

    Reconstruction follows matching diagonal steps or a neighbour that preserves the optimal length. Ties can produce more than one valid LCS.

  3. 3

    Two rolling rows reduce memory when only the length is needed. Reconstructing the sequence requires retained decisions or a more advanced reconstruction strategy.

04 Count the cost

TIME

O(mn) for input lengths m and n

SPACE

O(mn) table; length-only version uses O(n)

Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.

05 Your next move

A SMALL MISSION

Compute the LCS length with rolling rows and test an empty input.

Reveal one possible solution +
one_possible_solution.py
def lcs_length(a, b):
    previous = [0] * (len(b) + 1)
    for character in a:
        current = [0]
        for j, other in enumerate(b, start=1):
            current.append(previous[j-1] + 1 if character == other else max(previous[j], current[-1]))
        previous = current
    return previous[-1]
print(lcs_length("CODE", "CONE"))
print(lcs_length("", "CONE"))

06 Check your reasoning

QUICK SIGNAL CHECK

May a subsequence skip characters?

ANOTHER PATTERN IN YOUR TOOLKIT.

Understand it. Then own it.

Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.

Built with curiosity. By Navan Sami. ↗Patterns over panic. One step at a time.