Skip to content
DSA Visualizerpreview

Longest common subsequence

A table over every pair of prefixes: a shared letter extends the diagonal, otherwise keep the better neighbour.

O(m × n) time · O(m × n) space

Two wordsABCBDAB, BDCABA

dp[i][j] = longest common subsequence of the first i letters of ABCBDAB and the first j of BDCABA. Row 0 and column 0 are 0.

View
Table for "ABCBDAB" down the side and "BDCABA" across the top; 0 of 42 cells filled.

Table for "ABCBDAB" down the side and "BDCABA" across the top; 0 of 42 cells filled.

  • compare
  • swap or write
  • settled

1 / 44

Speed

Space play · ← → step · Home End jump · drag the strip to scrub