{"id":834,"date":"2024-10-14T14:21:28","date_gmt":"2024-10-14T08:51:28","guid":{"rendered":"https:\/\/codexplained.in\/?p=834"},"modified":"2025-11-24T15:43:31","modified_gmt":"2025-11-24T10:13:31","slug":"find-minimum-edit-distance-levenshtein-distance","status":"publish","type":"post","link":"https:\/\/codexplained.in\/?p=834","title":{"rendered":"Find Minimum Edit Distance (Levenshtein Distance)"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Problem Statement<\/h3>\n\n\n\n<p>Given two strings, calculate the minimum number of edits required to transform the first string into the second. The allowed operations are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Insertion of a character<\/li>\n\n\n\n<li>Deletion of a character<\/li>\n\n\n\n<li>Substitution of one character for another<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">Key Concepts<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Dynamic Programming<\/strong>: This method breaks down the problem into smaller subproblems and builds up solutions using previously computed results.<\/li>\n\n\n\n<li><strong>State Representation<\/strong>: We can use a 2D array <code>dp<\/code> where <code>dp[i][j]<\/code> represents the minimum edit distance between 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<\/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>: Initialize a 2D array <code>dp<\/code> of size <code>(m+1) x (n+1)<\/code>, where <code>m<\/code> is the length of string <code>X<\/code> and <code>n<\/code> is the length of string <code>Y<\/code>.<\/li>\n\n\n\n<li><strong>Step 2<\/strong>: Fill the first row and the first column to represent the cost of converting between an empty string and a substring of the other string.<\/li>\n\n\n\n<li><strong>Step 3<\/strong>: Iterate through each character of both strings to fill the <code>dp<\/code> table based on the minimum operations required.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">C Program for Minimum Edit Distance<\/h3>\n\n\n\n<p>Here\u2019s a complete C program to compute the Minimum Edit Distance:<\/p>\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 calculate the minimum edit distance\nint minEditDistance(char* X, char* Y) {\n    int m = strlen(X);\n    int n = strlen(Y);\n    \n    \/\/ Create a DP table\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    \/\/ Initialize the first row and column\n    for (int i = 0; i &lt;= m; i++) {\n        dp&#x5B;i]&#x5B;0] = i; \/\/ Deletion cost\n    }\n    for (int j = 0; j &lt;= n; j++) {\n        dp&#x5B;0]&#x5B;j] = j; \/\/ Insertion cost\n    }\n\n    \/\/ Fill the DP table\n    for (int i = 1; i &lt;= m; i++) {\n        for (int j = 1; j &lt;= n; j++) {\n            if (X&#x5B;i - 1] == Y&#x5B;j - 1]) {\n                dp&#x5B;i]&#x5B;j] = dp&#x5B;i - 1]&#x5B;j - 1]; \/\/ No operation needed\n            } else {\n                dp&#x5B;i]&#x5B;j] = 1 + (dp&#x5B;i - 1]&#x5B;j - 1] &lt; dp&#x5B;i]&#x5B;j - 1] ? \n                               (dp&#x5B;i - 1]&#x5B;j - 1] &lt; dp&#x5B;i]&#x5B;j - 1] ? \n                               dp&#x5B;i - 1]&#x5B;j - 1] : dp&#x5B;i]&#x5B;j - 1]) : \n                               (dp&#x5B;i]&#x5B;j - 1] &lt; dp&#x5B;i - 1]&#x5B;j] ? \n                               dp&#x5B;i]&#x5B;j - 1] : dp&#x5B;i - 1]&#x5B;j]));\n            }\n        }\n    }\n\n    \/\/ The minimum edit distance is in dp&#x5B;m]&#x5B;n]\n    int distance = dp&#x5B;m]&#x5B;n];\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\n    return distance;\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    \/\/ Calculate the minimum edit distance\n    int distance = minEditDistance(X, Y);\n    printf(&quot;Minimum Edit Distance (Levenshtein Distance): %d\\n&quot;, distance);\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>A 2D array <code>dp<\/code> is created, where <code>dp[i][j]<\/code> holds the minimum edit distance between 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>Initialization<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The first row represents the cost of converting from an empty string to substrings of <code>Y<\/code>, which is equal to the length of those substrings (insertion cost).<\/li>\n\n\n\n<li>The first column represents the cost of converting from substrings of <code>X<\/code> to an empty string, which is equal to the length of those substrings (deletion cost).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Filling the DP Table<\/strong>:\n<ul class=\"wp-block-list\">\n<li>We iterate through both strings, checking if the characters match. If they do, no additional cost is incurred. If they don\u2019t, we compute the minimum cost of the three possible operations (insertion, deletion, substitution).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Memory Management<\/strong>:\n<ul class=\"wp-block-list\">\n<li>The program dynamically allocates memory for the <code>dp<\/code> array and frees it after use 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:kitten\nEnter second string:sitting\n<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Output<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">javaCopy code<code>Minimum Edit Distance (Levenshtein Distance): 3\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Explanation of the Output<\/h3>\n\n\n\n<p>In this case, the minimum edit distance of <code>3<\/code> can be achieved by:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Substituting &#8216;k&#8217; with &#8216;s&#8217;<\/li>\n\n\n\n<li>Substituting &#8216;e&#8217; with &#8216;i&#8217;<\/li>\n\n\n\n<li>Inserting &#8216;g&#8217; at the end.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p>This C program efficiently computes the Minimum Edit Distance (Levenshtein Distance) between two strings using dynamic programming. It allows user input for flexibility and outputs the minimum number of edits required to convert one string into another. You can test various pairs of strings to see how the edit distance changes, making this approach useful in various applications, including spell checking, DNA sequence analysis, and more.<\/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>Problem Statement Given two strings, calculate the minimum number of edits required to transform the first string into the second. The allowed operations are: Key Concepts Dynamic Programming Approach C Program for Minimum Edit Distance Here\u2019s a complete C program to compute the Minimum Edit Distance: Explanation of the Code Input and Output Example Input [&hellip;]<\/p>\n","protected":false},"author":39,"featured_media":835,"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-834","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\/834","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=834"}],"version-history":[{"count":3,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/834\/revisions"}],"predecessor-version":[{"id":1426,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/posts\/834\/revisions\/1426"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=\/wp\/v2\/media\/835"}],"wp:attachment":[{"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=834"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=834"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codexplained.in\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=834"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}