Data Structures & Algorithms

Table of Contents

Longest common subsequence

Problem: “Find LCS of <N,I,A,C,U,E> and <N,I,C,E,A,C>.”

Solution: Set up a table (2D array):

j \ i0NIACUE
00000000
N0
I0
C0
E0
A0
C0

Then, for every cell:

The LCS length is the lowest rightmost cell. To find which elements are included in the subsequence, follow the arrows and record every cell that has a diagonal arrow pointing from it (it will be in reverse):

Diagram

LCS = 4 — [N, I, A, C]

Worst-case complexity: O(m × n)

Extending:

To turn this into longest common increasing subsequence, create an array of elements from minimum to maximum, and then find LCS between this array and the input.