Longest Common Subsequence (LCS) with Memoization
/** * Computes the length of the Longest Common Subsequence (LCS) of two strings * using recursion with memoization (dynamic programming). * * @param {string} text1 The first string. * @param {string} text2 The second string. * @returns {number} The length of the LCS. */ function...
This function calculates the length of the Longest Common Subsequence (LCS) between two strings. The LCS problem is a classic computer science problem that finds the longest subsequence common to both sequences. It's wid...
The algorithm computes the LCS length using a top-down dynamic programming approach with memoization. The core idea is that the LCS of two strings `text1` and `text2` can be defined recursively. If the last characters of `text1` and `text2` match, then the LCS length is 1 plus the LCS length of the strings without their last characters. If they don't match, the LCS length is the maximum of (LCS of `text1` without its last character and `text2`) and (LCS of `text1` and `text2` without its last character). Memoization is used to store the results of subproblems (LCS of prefixes) in a table (`memo`) to avoid redundant computations, significantly improving performance. The time complexity is O(m*n), where m and n are the lengths of the two strings, because each subproblem (defined by a pair of indices `i` and `j`) is computed only once. The space complexity is also O(m*n) due to the memoization table.
function longestCommonSubsequence(text1, text2): m = length of text1 n = length of text2 memo = 2D array of size (m+1)x(n+1), initialized with -1 function solve(i, j): if i == 0 or j == 0: return 0 if memo[i][j] is not -...