Skip to main content

Longest Common Subsequence (LCS)

Definition​

The Longest Common Subsequence (LCS) Algorithm is a dynamic programming approach used to find the longest subsequence present in given sequences

Practice​

longest_common_subsequence(sequence1, sequence2):
m = length(sequence1)
n = length(sequence2)
matrix = initialize_matrix(m, n)

for i from 1 to m:
for j from 1 to n:
if sequence1[i-1] == sequence2[j-1]:
matrix[i][j] = matrix[i-1][j-1] + 1
else:
matrix[i][j] = max(matrix[i-1][j], matrix[i][j-1])

return reconstruct_lcs(matrix, sequence1, sequence2, m, n)

reconstruct_lcs(matrix, sequence1, sequence2, m, n):
lcs = []
i = m
j = n

while i > 0 and j > 0:
if sequence1[i-1] == sequence2[j-1]:
lcs.push(sequence1[i-1])
i -= 1
j -= 1
else if matrix[i-1][j] > matrix[i][j-1]:
i -= 1
else:
j -= 1

return reverse(lcs)

initialize_matrix(m, n):
matrix = new matrix with dimensions (m+1) x (n+1)
for i from 0 to m:
matrix[i][0] = 0
for j from 0 to n:
matrix[0][j] = 0
return matrix