Longest Common Substring

Finding the longest shared sequence of characters between two strings using Dynamic Programming.

The Problem

Given two strings, S1 and S2, find the longest string that is a substring of both.

Example:
S1 = "ABABC"
S2 = "BABCA"
Common Substring: "ABC" (Length 3)

Dynamic Programming Approach

We create a 2D table (matrix) DP of size (m+1) x (n+1).

  • If S1[i] == S2[j], then DP[i][j] = DP[i-1][j-1] + 1.
  • If they don't match, DP[i][j] = 0.

The maximum value in the entire matrix is the length of the Longest Common Substring.

Python Implementation

def longest_common_substring(s1, s2):
    m = len(s1)
    n = len(s2)
    
    # Create a 2D table filled with 0
    dp = [[0 for x in range(n + 1)] for y in range(m + 1)]
    
    max_length = 0
    
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if s1[i-1] == s2[j-1]:
                dp[i][j] = dp[i-1][j-1] + 1
                max_length = max(max_length, dp[i][j])
            else:
                dp[i][j] = 0
                
    return max_length

# Test
print(longest_common_substring("ABABC", "BABCA")) 
# Output: 3

Time Complexity

O(m * n), where m and n are lengths of the strings. We visit every cell in the matrix exactly once.