Log In Sign Up
Day 32

Day 32: Longest Common Subsequence

32/60 Days

Longest Common Subsequence (LCS) #

Welcome to Day 32 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore the Longest Common Subsequence (LCS) problem, a classic example of dynamic programming.

What is the Longest Common Subsequence? #

The Longest Common Subsequence problem is to find the longest subsequence common to all sequences in a set of sequences. Unlike substrings, subsequences are not required to occupy consecutive positions within the original sequences.

For example, the LCS of “ABCDGH” and “AEDFHR” is “ADH” of length 3.

Naive Recursive Approach #

Let’s start with a naive recursive implementation:

 1def lcs_naive(X, Y, m, n):
 2    if m == 0 or n == 0:
 3        return 0
 4    elif X[m-1] == Y[n-1]:
 5        return 1 + lcs_naive(X, Y, m-1, n-1)
 6    else:
 7        return max(lcs_naive(X, Y, m, n-1), lcs_naive(X, Y, m-1, n))
 8
 9# Example usage
10X = "ABCDGH"
11Y = "AEDFHR"
12print(f"Length of LCS is {lcs_naive(X, Y, len(X), len(Y))}")

This approach has a time complexity of O(2^n) in the worst case, making it inefficient for longer sequences.

Dynamic …