AlgoMaster Logo

Longest Common Subsequence

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursion

Intuition:

The simplest way to solve this problem is to use recursion. For each character in the two strings, we have two choices:

  1. If the current characters in both strings are the same, consider the character as part of the subsequence and move to the next character in both strings.
  2. If the characters do not match, independently consider the two possibilities:
    • Exclude the current character of the first string and include the possibility of the rest.
    • Exclude the current character of the second string and include the possibility of the rest.

The maximum of these choices will give us the length of the longest common subsequence.

Code:

2. Recursion with Memoization (Top-Down DP)

Intuition:

Recursion leads to overlapping subproblems. By storing and reusing already computed results, we can reduce unnecessary computations. We use a 2D array (memoization table) to store the lengths of the longest common subsequence for substrings seen so far.

Code:

3. Dynamic Programming (Bottom-Up DP)

Intuition:

Instead of solving the problem recursively, use an iterative approach by filling up a DP table where dp[i][j] represents the length of the longest common subsequence of text1[0:i-1] and text2[0:j-1].

  • Initialize a table with dimensions ((m+1) \times (n+1)) to zero.
  • Fill the table iteratively based on character match:
    • If characters match, dp[i][j] = 1 + dp[i-1][j-1].
    • Otherwise, dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]).

Code: