Skip to problem
←

Longest Common Substring

Medium 0 attempts

Given two strings s1 and s2, return the length of their longest common substring. A substring consists of consecutive characters; you cannot skip characters as you can in a subsequence.

The substring may start at different positions in the two strings. Comparisons are case-sensitive: "A" and "a" differ. Return 0 if no character is shared.

For "ABCDGH" and "ACDGHR", the common substring "CDGH" has length 4. For "ABC" and "ACB", the answer is 1: "AB" is a common subsequence, but it is not contiguous in the second string.

Function contract

Implement longestCommonSubstring(s1, s2). Receive two nonempty strings of English letters. Comparisons are case-sensitive.

Output: Return the length of the longest contiguous substring present in both strings. Return 0 if they share no character.

Example 1

Input
s1 = "ABCDGH"
s2 = "ACDGHR"
Output
4

Example 2

Input
s1 = "ABC"
s2 = "ACB"
Output
1
Constraints
  • 1 <= s1.length, s2.length <= 500
  • s1 and s2 contain uppercase and lowercase English letters

Approach: Dynamic Programming

Create a 2D DP table where dp[i][j] stores the length of the longest common suffix ending at s1[i-1] and s2[j-1]. If characters match, dp[i][j] = dp[i-1][j-1] + 1. On a mismatch the entry stays zero: a contiguous match cannot cross that position. Track the maximum across every cell, since the best substring need not end at the last character of either string.

javascript
function longestCommonSubstring(s1, s2) {
  const m = s1.length, n = s2.length;
  let max = 0;
  const dp = Array.from({length: m + 1}, () => Array(n + 1).fill(0));
  for (let i = 1; i <= m; i++)
    for (let j = 1; j <= n; j++)
      if (s1[i-1] === s2[j-1]) {
        dp[i][j] = dp[i-1][j-1] + 1;
        max = Math.max(max, dp[i][j]);
      }
  return max;
}

Time Complexity: O(m × n)

Space Complexity: O(m × n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript