Skip to content

Algorithms

Longest Common Subsequence (DP)

O(n·m) time and O(n·m) space, where n and m are the two string lengths — one grid cell for each pair of positions.

The idea, in plain English

Imagine two friends each write out the story of their week, one event per line. The longest common subsequence is the longest thread of events that show up in both stories, in the same order. The events do not need to sit back-to-back, since other unrelated events can sit in between. It is not about matching whole chunks of text. It is about finding the longest 'both of us did these things, in this order' thread.

How it works

  1. 1Build a grid where cell (i, j) answers: what is the longest common thread using only the first i letters of string A and the first j letters of string B?
  2. 2If the letters at those positions match, the answer is one better than the diagonal cell before it. You extend the thread by one letter.
  3. 3If they do not match, the answer is the bigger of two neighboring cells: 'drop this letter from A' or 'drop this letter from B'. Fill the whole grid this way, then walk it backward from the corner to read out the actual matching letters.

When you'd use it

Use it to compare two sequences for shared structure — comparing two versions of a file, comparing DNA sequences, spell-check suggestions, or measuring how similar two pieces of text really are, beyond a simple equality check.

Common beginner mistakes

  • Confusing 'subsequence' with 'substring'. A subsequence can skip letters and does not need to sit together, so 'ACE' is a subsequence of 'ABCDE' even though the letters are not next to each other.
  • Getting the grid's off-by-one positions wrong. Row and column 0 represent 'zero letters used', so the actual string characters start at position i - 1 and j - 1, not i and j.

Try it — edit and run

Click the code to edit · press ⌘/Ctrl+↵ to run

Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.

Expected output — hit Run to try it
String A: ABCBDAB
String B: BDCABA
LCS length: 4
LCS sequence: BCBA

See it in motion

Watch the grid fillLCS gridO(n·m) time and O(n·m) space, where n and m are the two string lengths — one grid cell for each pair of positions.

Ready. Fill the grid row by row to find the longest shared thread.

ABCBDAB · BDCABA
Strings
0
Matches hit
—
LCS length
…
LCS
ComputingReads (diagonal / up / left)AnswerNot filled yet

Not sure this is the right topic? See the learning paths → or where this leads →