Given two strings, find the length of their longest common substring (contiguous sequence). Unlike subsequence, substring must be contiguous — mismatch resets to 0.
"abcdxyz", "xyzabcd"4Unlike subsequence, substring is contiguous. Any mismatch resets the cell to 0. Match extends the diagonal streak. Answer = peak value in table; trace back diagonally for actual substring.
Checking every substring of one string against the other is O(n) cubed or worse. Prefix tables again give a quadratic solution.
Let dp of i and j be the length of the common substring that ends exactly at character i of the first string and character j of the second. If the characters match, extend the diagonal: dp of i −1, j −1, plus 1. If they do not match, the run is broken, so the value is 0. That reset to 0 is the only difference from the subsequence version. The answer is the largest value anywhere in the table, not the bottom right cell.
A mismatch resets a substring to 0. The answer is the maximum cell, wherever it is.
Run the animation above on your own input, or watch the 1:48 video explanation of Longest Common Substring with a dry run and Java code.