Module P-14·18 min read

Longest common subsequence, longest increasing subsequence, edit distance, and matrix path problems.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

Module P-14 — Dynamic Programming IV: LCS, LIS, Edit Distance, and Matrix Paths

What this module covers: Module P-13's 2D DP compared one sequence against a resource constraint. This module covers 2D DP where the two dimensions are two separate sequences being compared against each other — the shape behind diff tools, spell-checkers, and fuzzy matching — plus a weighted variant of Module P-13's grid-path counting.


Longest Common Subsequence (LCS)

Given two strings, find the length of the longest subsequence common to both — not necessarily contiguous, just in the same relative order.

typescript

dp[i][j] = the LCS length considering only the first i characters of s1 and the first j characters of s2. On a match, extending the LCS found in the smaller subproblem (dp[i-1][j-1], both strings one character shorter) by one is clearly correct. On a mismatch, the current characters can't both be part of the LCS together, so the best answer must come from dropping one character from one side or the other — taking whichever of those two gives the longer result. Both dimensions here represent positions within separate sequences, unlike Module P-13's knapsack, where the second dimension was a resource budget.


Longest Increasing Subsequence (LIS)

Given one sequence, find the length of its longest strictly increasing subsequence (not necessarily contiguous).

typescript

This version is O(n²) — for each position i, it checks every earlier position j. A key subtlety worth naming: dp[i] must specifically mean "the LIS ending exactly at index i," not "the LIS within the first i elements" — because a later element might need to extend a subsequence that ends partway through the array, not necessarily the overall best-so-far. The final answer is the maximum across the whole dp array, since the overall longest subsequence could end anywhere. (An O(n log n) version exists, maintaining a separate array of "smallest tail value for each achievable subsequence length" and using Module F-11's binary search to find where each new element belongs — a genuinely different technique layered on top of the same underlying problem, not covered in full here.)


Edit Distance (Levenshtein Distance)

The minimum number of single-character insertions, deletions, or substitutions needed to transform one string into another — the exact metric behind "did you mean...?" spell-check suggestions.

typescript

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.