Skip to content
Advertisement

Python: Length of longest common subsequence of lists

Is there a built-in function in python which returns a length of longest common subsequence of two lists?

JavaScript

I tried to find longest common subsequence and then get length of it but I think there must be a better solution.

Advertisement

Answer

You can easily retool a Longest Common Subsequence (LCS) into a Length of the Longest Common Subsequence (LLCS):

JavaScript

Demo:

JavaScript

If you wanted the longest common substring (a different, but related problem, where the subsequence is contiguous), use:

JavaScript

This is very similar to the lcs_length dynamic programming approach, but we track the maximum length found so far (since it is no longer guaranteed the last element in the table is the maximum).

This returns 3:

JavaScript

A sparse table variant to not have to track all the 0s (use this if a and b are potentially very large):

JavaScript
Advertisement