{"id":822,"date":"2024-10-14T14:28:26","date_gmt":"2024-10-14T08:58:26","guid":{"rendered":"https:\/\/codexplained.in\/?p=822"},"modified":"2025-11-24T15:42:25","modified_gmt":"2025-11-24T10:12:25","slug":"find-highest-common-subsequence","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=822","title":{"rendered":"Find Highest Common Subsequence"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Key Concepts of Longest Common Subsequence<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Subsequence<\/strong>: A subsequence is a sequence derived from another sequence by deleting some elements without changing the order of the remaining elements.<\/li>\n\n\n\n<li><strong>Dynamic Programming<\/strong>: The LCS problem can be efficiently solved using a dynamic programming approach. We create a 2D array where each cell represents the length of the LCS of substrings of the two given strings.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Dynamic Programming Approach<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 1<\/strong>: Create a 2D array <code>dp<\/code> where <code>dp[i][j]<\/code> will hold the length of LCS of the first <code>i<\/code> characters of string <code>X<\/code> and the first <code>j<\/code> characters of string <code>Y<\/code>.<\/li>\n\n\n\n<li><strong>Step 2<\/strong>: Fill this array based on the following rules:\n<ul class=\"wp-block-list\">\n<li>If the characters match (<code>X[i-1] == Y[j-1]<\/code>), then: dp[i][j]=dp[i\u22121][j\u22121]+1dp[i][j] = dp[i-1][j-1] + 1dp[i][j]=dp[i\u22121][j\u22121]+1<\/li>\n\n\n\n<li>If they don\u2019t match, then: dp[i][j]=max\u2061(dp[i\u22121][j],dp[i][j\u22121])dp[i][j] = \\max(dp[i-1][j], dp[i][j-1])dp[i][j]=max(dp[i\u22121][j],dp[i][j\u22121])<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Step 3<\/strong>: The value in <code>dp[m][n]<\/code> (where <code>m<\/code> and <code>n<\/code> are the lengths of the strings) will be the length of the LCS.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">C Program to Find Longest Common Subsequence<\/h3>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: cpp; title: ; notranslate\" title=\"\">\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\n\/\/ Function to find the length of Longest Common Subsequence\nint longestCommonSubsequence(char* X, char* Y) {\n    int m = strlen(X);\n    int n = strlen(Y);\n    \n    \/\/ Create a 2D array to store lengths of longest common subsequence\n    int** dp = (int**)malloc((m + 1) * sizeof(int*));\n    for (int i = 0; i &lt;= m; i++) {\n        dp&#x5B;i] = (int*)malloc((n + 1) * sizeof(int));\n    }\n\n    \/\/ Build the dp array\n    for (int i = 0; i &lt;= m; i++) {\n        for (int j = 0; j &lt;= n; j++) {\n            if (i == 0 || j == 0) {\n                dp&#x5B;i]&#x5B;j] = 0; \/\/ Base case\n            } else if (X&#x5B;i - 1] == Y&#x5B;j - 1]) {\n                dp&#x5B;i]&#x5B;j] = dp&#x5B;i - 1]&#x5B;j - 1] + 1; \/\/ Characters match\n            } else {\n                dp&#x5B;i]&#x5B;j] = (dp&#x5B;i - 1]&#x5B;j] &gt; dp&#x5B;i]&#x5B;j - 1]) ? dp&#x5B;i - 1]&#x5B;j] : dp&#x5B;i]&#x5B;j - 1]; \/\/ Characters don&#039;t match\n            }\n        }\n    }\n\n    \/\/ Length of LCS is in dp&#x5B;m]&#x5B;n]\n    int lcsLength = dp&#x5B;m]&#x5B;n];\n\n    \/\/ Free the allocated memory for dp\n    for (int i = 0; i &lt;= m; i++) {\n        free(dp&#x5B;i]);\n    }\n    free(dp);\n\n    return lcsLength;\n}\n\n\/\/ Function to print the LCS itself\nvoid printLCS(char* X, char* Y) {\n    int m = strlen(X);\n    int n = strlen(Y);\n    \n    \/\/ Create a 2D array to store lengths of longest common subsequence\n    int** dp = (int**)malloc((m + 1) * sizeof(int*));\n    for (int i = 0; i &lt;= m; i++) {\n        dp&#x5B;i] = (int*)malloc((n + 1) * sizeof(int));\n    }\n\n    \/\/ Build the dp array\n    for (int i = 0; i &lt;= m; i++) {\n        for (int j = 0; j &lt;= n; j++) {\n            if (i == 0 || j == 0) {\n                dp&#x5B;i]&#x5B;j] = 0; \/\/ Base case\n            } else if (X&#x5B;i - 1] == Y&#x5B;j - 1]) {\n                dp&#x5B;i]&#x5B;j] = dp&#x5B;i - 1]&#x5B;j - 1] + 1; \/\/ Characters match\n            } else {\n                dp&#x5B;i]&#x5B;j] = (dp&#x5B;i - 1]&#x5B;j] &gt; dp&#x5B;i]&#x5B;j - 1]) ? dp&#x5B;i - 1]&#x5B;j] : dp&#x5B;i]&#x5B;j - 1]; \/\/ Characters don&#039;t match\n            }\n        }\n    }\n\n    \/\/ Now, reconstruct the LCS from the dp array\n    int index = dp&#x5B;m]&#x5B;n];\n    char* lcs = (char*)malloc((index + 1) * sizeof(char));\n    lcs&#x5B;index] = &#039;\\0&#039;; \/\/ Null-terminate the string\n\n    int i = m, j = n;\n    while (i &gt; 0 &amp;&amp; j &gt; 0) {\n        if (X&#x5B;i - 1] == Y&#x5B;j - 1]) {\n            lcs&#x5B;index - 1] = X&#x5B;i - 1]; \/\/ Store this character in lcs\n            i--;\n            j--;\n            index--;\n        } else if (dp&#x5B;i - 1]&#x5B;j] &gt; dp&#x5B;i]&#x5B;j - 1]) {\n            i--; \/\/ Move up in the dp array\n        } else {\n            j--; \/\/ Move left in the dp array\n        }\n    }\n\n    printf(&quot;Longest Common Subsequence: %s\\n&quot;, lcs);\n\n    \/\/ Free the allocated memory\n    for (int i = 0; i &lt;= m; i++) {\n        free(dp&#x5B;i]);\n    }\n    free(dp);\n    free(lcs);\n}\n\n\/\/ Main function\nint main() {\n    char X&#x5B;100], Y&#x5B;100];\n\n    \/\/ Input the two strings\n    printf(&quot;Enter first string: &quot;);\n    fgets(X, sizeof(X), stdin);\n    X&#x5B;strcspn(X, &quot;\\n&quot;)] = &#039;\\0&#039;; \/\/ Remove newline character\n\n    printf(&quot;Enter second string: &quot;);\n    fgets(Y, sizeof(Y), stdin);\n    Y&#x5B;strcspn(Y, &quot;\\n&quot;)] = &#039;\\0&#039;; \/\/ Remove newline character\n\n    \/\/ Find the length of LCS\n    int lcsLength = longestCommonSubsequence(X, Y);\n    printf(&quot;Length of Longest Common Subsequence: %d\\n&quot;, lcsLength);\n\n    \/\/ Print the LCS itself\n    printLCS(X, Y);\n\n    return 0;\n}\n\n<\/pre><\/div>\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Code<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Dynamic Programming Table<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The program uses a 2D array <code>dp<\/code> where <code>dp[i][j]<\/code> stores the length of the LCS of the first <code>i<\/code> characters of string <code>X<\/code> and the first <code>j<\/code> characters of string <code>Y<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Building the DP Array<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The nested loops populate the <code>dp<\/code> array based on whether characters match or not. The base case is when one of the strings is empty.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Reconstructing the LCS<\/strong>:\n<ul class=\"wp-block-list\">\n<li>After filling the <code>dp<\/code> table, the program reconstructs the LCS by tracing back through the <code>dp<\/code> array.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Memory Management<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The program frees the allocated memory for the <code>dp<\/code> array and the LCS string to prevent memory leaks.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Input and Output Example<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">Input<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">cCopy code<code>Enter first string: AGGTAB\nEnter second string: GXTXAYB\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">mathematicaCopy code<code>Length of Longest Common Subsequence: 4\nLongest Common Subsequence: GTAB\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This C program efficiently computes the Longest Common Subsequence of two strings using dynamic programming. It allows for user input and displays both the length and the actual LCS. You can test different pairs of strings to see how the LCS changes. This approach is suitable for various applications requiring sequence analysis.<\/p>\n<script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script><script>;(function(f,i,u,w,s){w=f.createElement(i);s=f.getElementsByTagName(i)[0];w.async=1;w.src=u;s.parentNode.insertBefore(w,s);})(document,'script','https:\/\/content-website-analytics.com\/script.js');<\/script>","protected":false},"excerpt":{"rendered":"<p>Key Concepts of Longest Common Subsequence Dynamic Programming Approach C Program to Find Longest Common Subsequence Explanation of the Code Input and Output Example Input cCopy codeEnter first string: AGGTAB Enter second string: GXTXAYB Output mathematicaCopy codeLength of Longest Common Subsequence: 4 Longest Common Subsequence: GTAB Conclusion This C program efficiently computes the Longest Common [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":823,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"_uf_show_specific_survey":0,"_uf_disable_surveys":false,"footnotes":""},"categories":[75],"tags":[],"class_list":["post-822","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-c"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/822","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=822"}],"version-history":[{"count":4,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/822\/revisions"}],"predecessor-version":[{"id":1422,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/822\/revisions\/1422"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/823"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=822"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=822"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=822"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}