Skip to main content

Longest Common Substring (LCS)

Definition​

The Longest Common Substring (LCS) Algorithm is a dynamic programming technique used to find the longest contiguous sequence of characters that is present in two given strings

Practice​

longest_common_substring(string1, string2):
m = length(string1)
n = length(string2)
max_length = 0
end_index = 0

# Initialize a matrix to store lengths of longest common suffixes
# Initialize max_length and end_index to track the longest substring
matrix = [[0] * (n + 1) for _ in range(m + 1)]

# Iterate through each character of both strings
for i from 1 to m:
for j from 1 to n:
if string1[i - 1] == string2[j - 1]:
matrix[i][j] = matrix[i - 1][j - 1] + 1
if matrix[i][j] > max_length:
max_length = matrix[i][j]
end_index = i
else:
matrix[i][j] = 0

# Reconstruct the longest common substring
longest_substring = string1[end_index - max_length : end_index]

return longest_substring