Longest common substring

Pattern: Strings DP

medium

A common substring must be unbroken. dp[i][j] is the length of the common block ending at a[i-1] and b[j-1]: diagonal + 1 on a match, 0 otherwise. The answer is the largest value anywhere.

The problem

Return the length of the longest string that appears as a contiguous substring of both s1 and s2.

Think first

  • What happens to a block when characters differ?
  • What does a cell mean?
  • Where is the answer?

Hints

    Brute force, and why it fails

    Check every pair of starting positions: O(m × n × min(m, n)).

    The key insight

    A block ending at (i, j) extends the block ending at (i - 1, j - 1), so each cell is one comparison.

    Dry run

    run2

    'ABCDGH' and 'ACDGHR'. 'C' matches: 1; then 'D': 2.

    Step 1 of 2

    The plan

    dp[i][j] = dp[i-1][j-1] + 1 if a[i-1] == b[j-1] else 0
    best = max of dp
    

    Complexity

    Time
    O(m × n)
    Space
    O(n)

    Two rows.

    Edge cases

    • No common character: 0.
    • Identical strings.
    • One character.
    I've built my logic, show the code

    Java

    class Solution {
        public int longestCommonSubstr(String s1, String s2) {
            int m = s1.length(), n = s2.length(), best = 0;
            int[][] run = new int[m + 1][n + 1];    // run[i][j]: the common block ending exactly at s1[i - 1] and s2[j - 1]
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; j++)
                    if (s1.charAt(i - 1) == s2.charAt(j - 1)) {
                        run[i][j] = run[i - 1][j - 1] + 1;   // extend the block; a mismatch resets it to 0
                        best = Math.max(best, run[i][j]);
                    }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int longestCommonSubstr(string s1, string s2) {
            int m = static_cast<int>(s1.size()), n = static_cast<int>(s2.size()), best = 0;
            vector<vector<int>> run(m + 1, vector<int>(n + 1, 0));   // the common block ending at s1[i-1] and s2[j-1]
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; j++)
                    if (s1[i - 1] == s2[j - 1]) {
                        run[i][j] = run[i - 1][j - 1] + 1;   // extend the block; a mismatch resets it to 0
                        best = max(best, run[i][j]);
                    }
            return best;
        }
    };

    Python

    class Solution:
        def longestCommonSubstr(self, s1: str, s2: str) -> int:
            prev, best = [0] * (len(s2) + 1), 0     # run lengths of common blocks ending at each position
            for a in s1:
                cur = [0]
                for j, b in enumerate(s2, 1):
                    cur.append(prev[j - 1] + 1 if a == b else 0)   # extend the block, or reset it
                best = max(best, max(cur))
                prev = cur
            return best

    Common mistakes

    • Using max(up, left) like LCS.
    • Returning the last cell.

    Similar problems