Bird
Raised Fist0
DSA Cprogramming

Longest Common Subsequence in DSA C

Choose your learning style10 modes available
Mental Model
Find the longest sequence of characters that appear in the same order in both strings, but not necessarily consecutively.
Analogy: Imagine two friends telling stories with some common events. The longest common subsequence is like the longest list of shared events they both mention in the same order, even if they skip some details.
String1: A B C D G H
String2: A E D F H R

LCS matrix (partial):
    Ø A E D F H R
Ø [0 0 0 0 0 0 0]
A [0 1 1 1 1 1 1]
B [0 1 1 1 1 1 1]
C [0 1 1 1 1 1 1]
D [0 1 1 2 2 2 2]
G [0 1 1 2 2 2 2]
H [0 1 1 2 2 3 3]
Dry Run Walkthrough
Input: String1: "ABCDGH", String2: "AEDFHR"
Goal: Find the longest common subsequence between the two strings
Step 1: Initialize a 2D array dp with zeros for lengths of substrings
dp matrix filled with zeros for dimensions (7 x 7) including empty prefix rows and columns
Why: We need a base to build subsequence lengths from empty prefixes
Step 2: Compare characters 'A' (String1[0]) and 'A' (String2[0]), they match, set dp[1][1] = dp[0][0] + 1 = 1
dp[1][1] = 1, rest zeros in first row and column
Why: Matching characters increase subsequence length by 1
Step 3: Compare 'B' (String1[1]) and 'E' (String2[1]), no match, set dp[2][2] = max(dp[1][2], dp[2][1]) = 1
dp[2][2] = 1, subsequence length remains 1
Why: No match, so take the best subsequence length from previous prefixes
Step 4: Compare 'D' (String1[3]) and 'D' (String2[2]), match, set dp[4][3] = dp[3][2] + 1 = 2
dp[4][3] = 2, subsequence length increases
Why: Matching characters extend the subsequence length
Step 5: Compare 'H' (String1[5]) and 'H' (String2[4]), match, set dp[6][5] = dp[5][4] + 1 = 3
dp[6][5] = 3, longest subsequence length found
Why: Last matching characters increase subsequence length to final value
Step 6: Trace back from dp[6][5] to find subsequence characters 'A', 'D', 'H'
LCS is "ADH"
Why: Backtracking recovers the actual subsequence from dp matrix
Result:
Longest Common Subsequence: "ADH" with length 3
Annotated Code
DSA C
#include <stdio.h>
#include <string.h>

// Function to find LCS length and print the subsequence
void longestCommonSubsequence(char* X, char* Y) {
    int m = strlen(X);
    int n = strlen(Y);
    int dp[m+1][n+1];

    // Build dp matrix
    for (int i = 0; i <= m; i++) {
        for (int j = 0; j <= n; j++) {
            if (i == 0 || j == 0) {
                dp[i][j] = 0; // base case: empty string
            } else if (X[i-1] == Y[j-1]) {
                dp[i][j] = dp[i-1][j-1] + 1; // match found
            } else {
                dp[i][j] = (dp[i-1][j] > dp[i][j-1]) ? dp[i-1][j] : dp[i][j-1]; // max of ignoring one char
            }
        }
    }

    // Length of LCS
    int index = dp[m][n];
    char lcs[index+1];
    lcs[index] = '\0';

    // Backtrack to find LCS string
    int i = m, j = n;
    while (i > 0 && j > 0) {
        if (X[i-1] == Y[j-1]) {
            lcs[index-1] = X[i-1];
            i--;
            j--;
            index--;
        } else if (dp[i-1][j] > dp[i][j-1]) {
            i--;
        } else {
            j--;
        }
    }

    printf("Longest Common Subsequence: %s\n", lcs);
}

int main() {
    char X[] = "ABCDGH";
    char Y[] = "AEDFHR";
    longestCommonSubsequence(X, Y);
    return 0;
}
if (i == 0 || j == 0) { dp[i][j] = 0; // base case: empty string }
initialize dp edges with zero for empty prefixes
else if (X[i-1] == Y[j-1]) { dp[i][j] = dp[i-1][j-1] + 1; // match found }
increase subsequence length when characters match
else { dp[i][j] = (dp[i-1][j] > dp[i][j-1]) ? dp[i-1][j] : dp[i][j-1]; // max of ignoring one char }
choose max subsequence length ignoring one character
while (i > 0 && j > 0) { if (X[i-1] == Y[j-1]) { lcs[index-1] = X[i-1]; i--; j--; index--; } else if (dp[i-1][j] > dp[i][j-1]) { i--; } else { j--; } }
backtrack dp matrix to reconstruct LCS string
OutputSuccess
Longest Common Subsequence: ADH
Complexity Analysis
Time: O(m*n) because we fill a matrix of size m by n once
Space: O(m*n) because we store subsequence lengths for all substring pairs
vs Alternative: Naive recursion without memoization is exponential O(2^(m+n)), so DP is much faster
Edge Cases
One or both strings empty
LCS length is zero and empty subsequence returned
DSA C
if (i == 0 || j == 0) {
    dp[i][j] = 0; // base case: empty string
}
Strings with no common characters
LCS length is zero and empty subsequence returned
DSA C
else {
    dp[i][j] = (dp[i-1][j] > dp[i][j-1]) ? dp[i-1][j] : dp[i][j-1]; // max of ignoring one char
}
Strings with all characters matching
LCS is the entire string
DSA C
else if (X[i-1] == Y[j-1]) {
    dp[i][j] = dp[i-1][j-1] + 1; // match found
}
When to Use This Pattern
When you need to find the longest sequence common to two sequences in order, use the Longest Common Subsequence pattern because it efficiently finds the maximum matching order.
Common Mistakes
Mistake: Not initializing the first row and column of dp matrix to zero
Fix: Explicitly set dp[i][0] and dp[0][j] to zero to handle empty substring cases
Mistake: Incorrectly indexing strings with dp indices (off by one)
Fix: Use X[i-1] and Y[j-1] when accessing characters because dp indices start from 1
Mistake: Not backtracking dp matrix to reconstruct the subsequence
Fix: Implement backtracking loop to build the LCS string from dp matrix
Summary
Finds the longest sequence of characters common to two strings in order.
Use when you want to compare two sequences and find their maximum ordered overlap.
The key insight is building a matrix of subsequence lengths and backtracking to get the sequence.

Practice

(1/5)
1. What does the Longest Common Subsequence (LCS) between two strings represent?
easy
A. The longest sequence of characters that appear in both strings in the same order, but not necessarily consecutively.
B. The longest substring that appears in both strings consecutively.
C. The total number of characters in both strings combined.
D. The shortest sequence of characters that can be removed to make the strings identical.

Solution

  1. 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.
  2. Step 2: Differentiate from substring and other concepts

    Unlike substring, LCS does not require characters to be consecutive. It is about order and presence.
  3. Final Answer:

    The longest sequence of characters that appear in both strings in the same order, but not necessarily consecutively. -> Option A
  4. Quick Check:

    LCS = longest ordered common sequence [OK]
Hint: LCS is about order, not consecutive characters [OK]
Common Mistakes:
  • Confusing LCS with longest common substring
  • Thinking characters must be consecutive
  • Mixing LCS with string length or edits
2. Which of the following is the correct way to declare a 2D array in C for storing LCS lengths of two strings of length m and n?
easy
A. int lcs[m][n];
B. int lcs[m-1][n-1];
C. int lcs[m+1][n+1];
D. int lcs[m*n];

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    int lcs[m+1][n+1]; -> Option C
  4. Quick Check:

    DP table size = (m+1) x (n+1) [OK]
Hint: Add 1 to lengths for DP table size [OK]
Common Mistakes:
  • Using m or n instead of m+1 or n+1
  • Declaring 1D array instead of 2D
  • Using multiplication instead of 2D array
3. What is the output of the following C code snippet that computes the length of LCS for strings "ABCBDAB" and "BDCABA"?
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;
}
medium
A. 6
B. 3
C. 5
D. 4

Solution

  1. Step 1: Understand the DP table filling

    The code fills the LCS table using standard DP approach comparing characters of X and Y.
  2. 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.
  3. 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.
  4. Final Answer:

    4 -> Option D
  5. Quick Check:

    LCS length for given strings = 4 [OK]
Hint: Trace DP table or recall classic LCS example [OK]
Common Mistakes:
  • Confusing LCS length with substring length
  • Off-by-one errors in indexing
  • Misreading the strings or code logic
4. Identify the error in the following C code snippet intended to compute the LCS length of two strings X and Y:
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];
}
medium
A. Indexing X[i] and Y[j] should be X[i-1] and Y[j-1].
B. Array size should be lcs[m+1][n+1] instead of lcs[m][n].
C. Initialization loops should start from 1, not 0.
D. Return statement should be lcs[m-1][n-1] instead of lcs[m][n].

Solution

  1. Step 1: Check array size and initialization

    The array size (m+1) x (n+1) and initialization loops are correct for the DP table.
  2. 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].
  3. Final Answer:

    Indexing X[i] and Y[j] should be X[i-1] and Y[j-1]. -> Option A
  4. Quick Check:

    String indexing off by one error [OK]
Hint: Remember C strings start at index 0 [OK]
Common Mistakes:
  • Using wrong indices for string characters
  • Ignoring array size for DP table
  • Incorrect initialization loop ranges
5. Given two strings X = "AGGTAB" and Y = "GXTXAYB", write a C function to print the actual Longest Common Subsequence (LCS) string, not just its length. Which approach correctly reconstructs the LCS from the DP table?
hard
A. Start from lcs[0][0], move right or down to find matching characters and build LCS forward.
B. Start from lcs[m][n], move diagonally up-left if characters match, else move in direction of larger value until reaching lcs[0][0].
C. Use recursion without memoization to print LCS directly from strings.
D. Print characters from X that appear anywhere in Y without order consideration.

Solution

  1. Step 1: Understand LCS reconstruction from DP table

    After filling the DP table, start from bottom-right cell lcs[m][n] and move backwards.
  2. 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).
  3. Step 3: Continue until reaching lcs[0][0]

    Collect characters in reverse order and then reverse them to get the LCS string.
  4. 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 B
  5. Quick Check:

    Backtrack DP table from bottom-right to reconstruct LCS [OK]
Hint: Backtrack DP table from bottom-right to get LCS [OK]
Common Mistakes:
  • Trying to build LCS forward from top-left
  • Ignoring order of characters in reconstruction
  • Printing characters without checking DP table values
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard