Longest Common Subsequence
The Longest Common Subsequence (LCS) problem is a classic computer science problem used to find the longest subsequence common to all sequences in a set of sequences (often just two sequences). A subsequence is a sequence derived from another sequence where some elements might be deleted without changing the order of the remaining elements.
Formal Definition
Given two sequences, X = x_1, x_2, ..., x_m and Y = y_1, y_2, ..., y_n, find a maximum-length common subsequence of X and Y.
Properties
- The LCS problem is a typical example of a problem that can be solved using dynamic programming.
- LCS is useful in data comparison applications, such as diff tools, bioinformatics for DNA sequencing, and version control systems.
Dynamic Programming Approach
The solution involves creating a 2D array dp where dp[i][j] represents the length of the LCS of the subarrays X[0:i] and Y[0:j].
Recurrence Relation
- If
x_i == y_j: