|
| 1 | +# 0005 Longest Common Subsequence ( L-A ) |
| 2 | + |
| 3 | +## Problem |
| 4 | + |
| 5 | +Given two strings, find the length of their longest common subsequence (LCS). A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. |
| 6 | + |
| 7 | +## Example 1 |
| 8 | + |
| 9 | +``` |
| 10 | +Input: |
| 11 | +str1 = "ABCDGH" |
| 12 | +str2 = "AEDFHR" |
| 13 | +
|
| 14 | +Output: |
| 15 | +The longest common subsequence is "ADH" with a length of 3. |
| 16 | +
|
| 17 | +Input: |
| 18 | +str1 = "AGGTAB" |
| 19 | +str2 = "GXTXAYB" |
| 20 | +
|
| 21 | +Output: |
| 22 | +The longest common subsequence is "GTAB" with a length of 4. |
| 23 | +``` |
| 24 | + |
| 25 | +## Solution Pseudocode |
| 26 | + |
| 27 | +```javascript |
| 28 | +function longestCommonSubsequence(str1, str2) { |
| 29 | + const m = str1.length; |
| 30 | + const n = str2.length; |
| 31 | + |
| 32 | + // Initialize a 2D array with 0 |
| 33 | + const lcs = Array(m + 1) |
| 34 | + .fill() |
| 35 | + .map(() => Array(n + 1).fill(0)); |
| 36 | + |
| 37 | + // Fill the 2D array with LCS lengths |
| 38 | + for (let i = 1; i <= m; i++) { |
| 39 | + for (let j = 1; j <= n; j++) { |
| 40 | + if (str1[i - 1] === str2[j - 1]) { |
| 41 | + lcs[i][j] = lcs[i - 1][j - 1] + 1; |
| 42 | + } else { |
| 43 | + lcs[i][j] = Math.max(lcs[i - 1][j], lcs[i][j - 1]); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + // Return the length of LCS |
| 49 | + return lcs[m][n]; |
| 50 | +} |
| 51 | + |
| 52 | +// Example usage |
| 53 | +const str1 = "ABCDGH"; |
| 54 | +const str2 = "AEDFHR"; |
| 55 | +const result = longestCommonSubsequence(str1, str2); |
| 56 | +console.log(result); // Output: 3 |
| 57 | + |
| 58 | +// Another example |
| 59 | +const str3 = "AGGTAB"; |
| 60 | +const str4 = "GXTXAYB"; |
| 61 | +const result2 = longestCommonSubsequence(str3, str4); |
| 62 | +console.log(result2); // Output: 4 |
| 63 | +``` |
| 64 | + |
| 65 | +## How it works |
| 66 | + |
| 67 | +- The code returns an object with two properties: `length`, which is the length of the longest common subsequence, and `sequence`, which is the actual subsequence itself. |
| 68 | +- It also includes a section of code to trace back the 2D array and find the actual LCS string. |
| 69 | +- The time complexity of this algorithm is O(mn), where m and n are the lengths of the input strings. |
| 70 | + |
| 71 | +## References |
| 72 | + |
| 73 | +- [Google](https://www.google.com/search?client=opera&q=Longest+Common+Subsequence&sourceid=opera&ie=UTF-8&oe=UTF-8) |
| 74 | + |
| 75 | +## Problem Added By |
| 76 | + |
| 77 | +- [Haris](https://github.com/harisdev-netizen) |
| 78 | + |
| 79 | +## Contributing |
| 80 | + |
| 81 | +Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. |
| 82 | + |
| 83 | +Please make sure to update tests as appropriate. |
0 commit comments