How to use Memoization (Top-Down Dynamic Programming) In Javascript

In this approach, we’ll use memoization to efficiently solve the problem by storing the results of previously solved subproblems.

  1. Create a memoization table (an array of arrays) to store the length of the LCS for different prefixes of the two strings.
  2. Define a recursive function to compute the LCS of two substrings, considering all possible cases.
  3. Use memoization to avoid redundant calculations by storing the results of subproblems in the memoization table.
  4. The base cases for the recursion are when either of the strings becomes empty. In such cases, the length of the LCS is 0.
  5. If the characters at the current positions in both strings match, we include this character in the LCS and recursively compute the LCS for the remaining substrings.
  6. If the characters don’t match, we consider two possibilities: either excluding the current character from the first string or excluding it from the second string, and we take the maximum of the lengths of the LCS obtained from these two possibilities.
  7. Finally, return the length of the LCS, which is stored in the memoization table.

Here’s the implementation in JavaScript:

JavaScript
function findLCS(s1, s2) {
    const memo = new Array(s1.length + 1).fill(null).map(() => new Array(s2.length + 1).fill(-1));

    function lcsHelper(i, j) {
        if (i === 0 || j === 0) return 0;

        if (memo[i][j] !== -1) return memo[i][j];

        if (s1[i - 1] === s2[j - 1])
            memo[i][j] = 1 + lcsHelper(i - 1, j - 1);
        else
            memo[i][j] = Math.max(lcsHelper(i - 1, j), lcsHelper(i, j - 1));

        return memo[i][j];
    }

    lcsHelper(s1.length, s2.length);

    let i = s1.length, j = s2.length;
    let lcs = "";

    while (i > 0 && j > 0) {
        if (s1[i - 1] === s2[j - 1]) {
            lcs = s1[i - 1] + lcs;
            i--;
            j--;
        } else if (memo[i - 1][j] > memo[i][j - 1])
            i--;
        else
            j--;
    }

    return lcs;
}

// Test Case
const s1 = "ABCDEK";
const s2 = "BDEGK";
console.log("Longest Common Subsequence: " + findLCS(s1, s2)); // Output: ABF

Output
Longest Common Subsequence: BDEK


JavaScript Program for Longest Common Subsequence

The longest common subsequence (LCS) is defined as the longest subsequence which is common in all given input sequences. In this article, we are given two strings, String1 and String2, the task is to find the longest common subsequence in both of the strings. A subsequence of a string can be achieved by deleting any number of elements from the string.

Example:

Input: 'ABCD' , 'AEBECED'
Output: 'ABCD'
Explanation: As 'ABCD' is common in both of the string and it is the longest string.

Table of Content

  • Brute force Method
  • Using DP array
  • Using Memoization (Top-Down Dynamic Programming)

Similar Reads

Brute force Method

In this approach, the idea is to generate all the sub-sequences and then to find the longest common subsequence in them. The problem with this approach is having very high time complexity. We need (2 to power n) time complexity to generate all the subsequences of a single string....

Using DP array

In this approach, We will use this DP array to get the longest common subsequence in both strings. By keeping track of a pointer , We will start to fill the string `str` from the end .We will start by positioning from the rightmost place in the DP array, which is denoted by `(i, j)` with `i = n` & `j = m`. At every cell, we will check whether `S1[i-1]` matches `S2[j-1]` or not. If they matches , it shows that this character can be included to the longest common substring.If we found the previous case we will add the character to end of the `str`. Then, we will move to diagonally top-left cell (↖) by decrementing both of `i` & `j`.However, it is obvious that if the characters do not match, it tells that the character is not the part of the longest common subsequence.In this case, we look whether value in the cell to the left (←) or above (↑) is greater. And move to the cell which has the greater value.We will keep on repeating this process until `i` and `j` are greater than 0. and if they become less than zero, we will exit the loop...

Using Memoization (Top-Down Dynamic Programming)

In this approach, we’ll use memoization to efficiently solve the problem by storing the results of previously solved subproblems....