Exploring the Longest Common Subsequence

Discover the Longest Common Subsequence (LCS) algorithm and its implementation in JavaScript using dynamic programming.

Longest Common Subsequence

Understanding the Problem

Before diving into code, let's grasp the essence of the problem. Given two sequences, we aim to find the longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order but not necessarily contiguous. This means we're interested in finding elements that appear consecutively in both sequences but with possible gaps in between.

The Dynamic Programming Approach

Dynamic programming offers an efficient solution to this problem by breaking it down into smaller subproblems and storing their solutions to avoid redundant calculations. At each step, we build upon the solutions of the smaller subproblems until we arrive at the solution for the entire problem.

Let's Dive into the Code

Without further ado, let's see how we can implement the LCS algorithm in JavaScript:

function longestCommonSubsequence(str1, str2) {
const m = str1.length;
const n = str2.length;

const dp = Array.from(Array(m + 1), () => Array(n + 1).fill(0));

for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
    if (str1[i - 1] = str2[j - 1]) {
        dp[i][j] = dp[i - 1][j - 1] + 1;
    } else {
        dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
    }
}
}

let i = m, j = n;
let result = '';
while (i > 0 && j > 0) {
if (str1[i - 1] === str2[j - 1]) {
    result = str1[i - 1] + result;
    i--;
    j--;
} else if (dp[i - 1][j] > dp[i][j - 1]) {
    i--;
} else {
    j--;
}
}

return result;
}

// Example usage:
const str1 = "ABCDGH";
const str2 = "AEDFHR";
console.log("Longest Common Subsequence:", longestCommonSubsequence(str1, str2)); // Output: "ADH"
In the code (str1[i - 1] = str2[j - 1]) should be (arr[i] === target) its beacause of the parsing issue

Breaking Down the Code

  • We start by initializing a 2D array dp to store the lengths of the longest common subsequences for different prefixes of the input sequences.
  • We iterate through each character of both strings and fill the dp array accordingly.
  • Finally, we backtrack through the dp array to reconstruct the longest common subsequence.

Conclusion

The LCS algorithm showcases the power and elegance of dynamic programming in solving complex problems efficiently. By breaking down the problem into smaller subproblems and leveraging memoization, we can achieve optimal solutions with relative ease.

In the world of software development, understanding and mastering such algorithms opens doors to solving a wide array of challenges effectively. So, embrace the beauty of dynamic programming and let it empower your problem-solving journey!

3 min read

back to blog

footer img

Raj Kapadia

Raj Kapadia is an ambitious software developer, an enthusiastic learner, and a devoted team player. With a strong foundation in coding principles and a passion for innovation, Raj is eager to leverage his problem-solving skills to contribute to challenging projects. He is an active participant in several open-source communities and is dedicated to continuous learning and growth.

Developer Logo

All rights Reserved © by Raj Kapadia 💚