Longest common subsequence

Learn Algorithms · 2:44

Listen on 93

Lyrics

[Verse 1]
Two strings sitting side by side
Need to find what they both provide
Not contiguous, that's the key
Subsequence means we can skip freely
Dynamic programming's our way
Build a table, step by step each day
Row by row and column clean
Finding patterns in between

[Chorus]
LCS, longest common subsequence
Break it down with table reference
Bottom up or top down flow
Match or skip, that's how we go
LCS, dynamic solution
Character by character resolution
When they match we add one more
When they don't we take the score

[Verse 2]
Start with empty string base case
Zero length in bottom space
If the characters are the same
Diagonal plus one's the game
If they differ, here's the rule
Take the maximum, that's our tool
Left or up, whichever's high
Copy that value, don't be shy

[Chorus]
LCS, longest common subsequence
Break it down with table reference
Bottom up or top down flow
Match or skip, that's how we go
LCS, dynamic solution
Character by character resolution
When they match we add one more
When they don't we take the score

[Bridge]
Traceback time to build the string
Follow arrows, that's the thing
Diagonal means we found a match
Left or up, no character catch
Applications everywhere
Edit distance, diff compare
Bioinformatics DNA
Version control, merge array

[Verse 3]
Time complexity quadratic
Space the same, but that's not tragic
Optimization possible though
Keep just two rows, let memory go
Memoization top down style
Recursion with a storage file
Both approaches get us there
Subsequences we can compare

[Chorus]
LCS, longest common subsequence
Break it down with table reference
Bottom up or top down flow
Match or skip, that's how we go
LCS, dynamic solution
Character by character resolution
When they match we add one more
When they don't we take the score

[Outro]
From empty strings to full compare
LCS is everywhere
Dynamic programming at its best
Longest common subsequence test

← Boyer-Moore | Knapsack (0/1 and unbounded) →