Skip to content
StackDecode
Dynamic programmingAnimated

Longest Common Substring

Like LCS but the match must be contiguous.

Time

O(n · m)

Extra space

O(n · m)

Use it for

Plagiarism and sequence matching.

How it works

  1. A substring must be contiguous (no skipping).
  2. Cell (i, j) = length of the common substring ENDING at letter i of A and letter j of B.
  3. If the letters match, cell = diagonal + 1; otherwise 0 (the run is broken).
  4. The answer is the largest cell anywhere in the table.

Watch it run

Loading animation…