Longest common subsequence

rock, electric guitar, powerful, anthem · 3:54

Listen on 93

Lyrics

[Verse 1]
Got two sequences laying on my desk tonight
String A and string B, gotta find what's right
Not the substring, not the common prefix game
Looking for the longest subsequence, that's my claim
Keep the order intact, but gaps are allowed
Skip some letters here and there, make the algorithm proud
Dynamic programming is the way we roll
Build a table step by step, that's how we reach our goal

[Chorus]
L-C-S, longest common subsequence
Bottom up approach, that's our reference
If they match, diagonal plus one
If they don't, take the maximum, we're never done
L-C-S, building table cell by cell
Two dimensions, stories that the numbers tell
From the bottom right, we trace it back
Following the path, staying on track

[Verse 2]
Initialize the base case, zeros on the edge
Empty string with anything, that's our pledge
Now we fill the matrix, row by row we go
If characters are equal, diagonal plus one to show
But when they're different, here's the clever part
Take the max of left and top, that's the art
Each cell represents the length we've found so far
Building up solutions like a superstar

[Chorus]
L-C-S, longest common subsequence
Bottom up approach, that's our reference
If they match, diagonal plus one
If they don't, take the maximum, we're never done
L-C-S, building table cell by cell
Two dimensions, stories that the numbers tell
From the bottom right, we trace it back
Following the path, staying on track

[Bridge]
Time complexity O of m times n
Space complexity same, let me say it again
But we can optimize if we only need the length
One dimensional array, that's our strength
Traceback reconstruction needs the full table though
To find the actual sequence, that's how we flow

[Verse 3]
Applications everywhere, from DNA alignment
To version control systems, perfect assignment
Edit distance calculation, diff algorithms too
Text comparison engines, LCS pulls us through
Bioinformatics relies on this foundation
Finding common patterns across the nation
From ATCG sequences to code repositories
LCS algorithm writes the greatest stories

[Chorus]
L-C-S, longest common subsequence
Bottom up approach, that's our reference
If they match, diagonal plus one
If they don't, take the maximum, we're never done
L-C-S, building table cell by cell
Two dimensions, stories that the numbers tell
From the bottom right, we trace it back
Following the path, staying on track

[Outro]
When you see two strings and need to find the link
LCS algorithm is faster than you think
Build it up, trace it back, optimal solution found
Longest common subsequence, wear it like a crown

← Fibonacci (memoized) | Longest increasing subsequence →