Longest Common Subsequence in DSA C - Time & Space Complexity
We want to understand how the time needed to find the longest common subsequence changes as the input strings get longer.
How does the work grow when the two strings become bigger?
Analyze the time complexity of the following code snippet.
int lcs(char *X, char *Y, int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
if (X[m - 1] == Y[n - 1]) {
return 1 + lcs(X, Y, m - 1, n - 1);
} else {
int a = lcs(X, Y, m, n - 1);
int b = lcs(X, Y, m - 1, n);
return (a > b) ? a : b;
}
}
This code finds the length of the longest common subsequence between two strings using recursion.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Recursive calls that explore all combinations of substrings.
- How many times: Each call splits into two more calls unless base case is reached, leading to many repeated calls.
As the lengths of the two strings increase, the number of recursive calls grows very fast because the function tries many substring pairs.
| Input Size (m, n) | Approx. Operations |
|---|---|
| 10, 10 | Millions of calls |
| 20, 20 | Trillions of calls |
| 30, 30 | Quintillions of calls |
Pattern observation: The work roughly doubles with each increase in string length, growing exponentially.
Time Complexity: O(2^(m+n))
This means the time needed grows very fast, doubling with each added character in the strings.
[X] Wrong: "The recursive calls only happen once per substring pair, so it should be much faster."
[OK] Correct: The recursion repeats many calls for the same substring pairs multiple times, causing exponential growth.
Understanding this complexity helps you explain why naive recursion is slow and why dynamic programming is needed to solve this problem efficiently.
"What if we use a table to store results of substring pairs (memoization)? How would the time complexity change?"
Practice
Solution
Step 1: Understand the definition of LCS
The LCS is a sequence that appears in both strings in the same order but not necessarily next to each other.Step 2: Differentiate from substring and other concepts
Unlike substring, LCS does not require characters to be consecutive. It is about order and presence.Final Answer:
The longest sequence of characters that appear in both strings in the same order, but not necessarily consecutively. -> Option AQuick Check:
LCS = longest ordered common sequence [OK]
- Confusing LCS with longest common substring
- Thinking characters must be consecutive
- Mixing LCS with string length or edits
Solution
Step 1: Understand LCS table size requirements
We need a table of size (m+1) x (n+1) to include empty prefixes for both strings.Step 2: Check array declaration syntax
int lcs[m+1][n+1]; correctly declares int lcs[m+1][n+1]; which fits the DP table size.Final Answer:
int lcs[m+1][n+1]; -> Option CQuick Check:
DP table size = (m+1) x (n+1) [OK]
- Using m or n instead of m+1 or n+1
- Declaring 1D array instead of 2D
- Using multiplication instead of 2D array
int main() {
char X[] = "ABCBDAB";
char Y[] = "BDCABA";
int m = 7, n = 6;
int lcs[8][7];
for (int i = 0; i <= m; i++) lcs[i][0] = 0;
for (int j = 0; j <= n; j++) lcs[0][j] = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (X[i-1] == Y[j-1])
lcs[i][j] = lcs[i-1][j-1] + 1;
else
lcs[i][j] = (lcs[i-1][j] > lcs[i][j-1]) ? lcs[i-1][j] : lcs[i][j-1];
}
}
printf("%d", lcs[m][n]);
return 0;
}Solution
Step 1: Understand the DP table filling
The code fills the LCS table using standard DP approach comparing characters of X and Y.Step 2: Calculate LCS length for given strings
The LCS of "ABCBDAB" and "BDCABA" is "BCBA" or "BDAB" with length 4, but careful tracing shows length 4 is correct. However, the code prints lcs[m][n], which is 4.Step 3: Re-evaluate LCS length
Actually, the longest common subsequence length is 4 or 5? Let's check carefully:
- "BCBA" length 4
- "BDAB" length 4
- But "BCABA" is not a subsequence.
Rechecking the classic example, the LCS length is 4.
But the code output is 4, so 4 is correct.Final Answer:
4 -> Option DQuick Check:
LCS length for given strings = 4 [OK]
- Confusing LCS length with substring length
- Off-by-one errors in indexing
- Misreading the strings or code logic
int lcs_length(char *X, char *Y, int m, int n) {
int lcs[m+1][n+1];
for (int i = 0; i <= m; i++) lcs[i][0] = 0;
for (int j = 0; j <= n; j++) lcs[0][j] = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (X[i] == Y[j])
lcs[i][j] = lcs[i-1][j-1] + 1;
else
lcs[i][j] = (lcs[i-1][j] > lcs[i][j-1]) ? lcs[i-1][j] : lcs[i][j-1];
}
}
return lcs[m][n];
}Solution
Step 1: Check array size and initialization
The array size (m+1) x (n+1) and initialization loops are correct for the DP table.Step 2: Check indexing of characters in strings
Strings in C are 0-indexed, but loops run from 1 to m/n, so characters should be accessed as X[i-1] and Y[j-1].Final Answer:
Indexing X[i] and Y[j] should be X[i-1] and Y[j-1]. -> Option AQuick Check:
String indexing off by one error [OK]
- Using wrong indices for string characters
- Ignoring array size for DP table
- Incorrect initialization loop ranges
Solution
Step 1: Understand LCS reconstruction from DP table
After filling the DP table, start from bottom-right cell lcs[m][n] and move backwards.Step 2: Move diagonally if characters match, else move towards larger neighbor
If characters match, include that character and move diagonally up-left; else move to the cell with larger value (up or left).Step 3: Continue until reaching lcs[0][0]
Collect characters in reverse order and then reverse them to get the LCS string.Final Answer:
Start from lcs[m][n], move diagonally up-left if characters match, else move in direction of larger value until reaching lcs[0][0]. -> Option BQuick Check:
Backtrack DP table from bottom-right to reconstruct LCS [OK]
- Trying to build LCS forward from top-left
- Ignoring order of characters in reconstruction
- Printing characters without checking DP table values
Ready to prove it?
Pass the test and this pattern moves unknown
