Lably
Skip to content

Longest common subsequence

Algorithmic problem on pairs of sequences

  • 14 min read
  • 7 chapters

Related on Lably

Through Computer science, Big O notation and Hash function

For example, consider the sequences (ABCD) and (ACBAD). They have five length-2 common subsequences: (AB), (AC), (AD), (BD), and (CD); two length-3 common subsequences: (ABD) and (ACD); and no longer common subsequences. So (ABD) and (ACD) are their longest common subsequences.

Complexity

For the general case of an arbitrary number of input sequences, the problem is NP-hard. When the number of sequences is constant, the problem is solvable in polynomial time by dynamic programming.

Given N sequences of lengths n1,...,nN, a naive search would test each of the 2n1 subsequences of the first sequence to determine whether they are also subsequences of the remaining sequences; each subsequence may be tested in time linear in the lengths of the remaining sequences, so the time for this algorithm would be

O(2n1∑i>1ni).

For the case of two sequences of n and m elements, the running time of the dynamic programming approach is O(n × m). For an arbitrary number of input sequences, the dynamic programming approach gives a solution in

O(N∏i=1Nni).

There exist methods with lower complexity, which often depend on the length of the LCS, the size of the alphabet, or both.

The LCS is not necessarily unique; in the worst case, the number of common subsequences is exponential in the lengths of the inputs, so the algorithmic complexity of listing all common subsequences must be at least exponential.

Sign in to keep reading

6 more chapters are free with a Lably account.

More in Computing and communication