{"id":346,"date":"2023-11-11T07:32:41","date_gmt":"2023-11-11T07:32:41","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=346"},"modified":"2023-11-14T07:09:12","modified_gmt":"2023-11-14T07:09:12","slug":"word-ladder","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/word-ladder\/","title":{"rendered":"Word Ladder Problem (C++, Java, and Python)"},"content":{"rendered":"\n<p>The word ladder is one of the problems that involves creative thinking. In this article, you will come to know about an approach to solving the word ladder problem, analyze their time and space complexity, and provide the solution in C++, Java, and Python.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the Word Ladder Problem?<\/strong><\/h2>\n\n\n\n<p><strong>The word ladder is the problem that involves finding the shortest word transformation from a given start word to a target word. <\/strong>Each transformation involves Transforming one word to another by changing only one letter at a time and each transformed word must exist in a provided word list.<\/p>\n\n\n\n<p>For example:<\/p>\n\n\n\n<p><strong>Start Word<\/strong> = \u201crat\u201d<\/p>\n\n\n\n<p><strong>End Word<\/strong> = \u201cbog\u201d<\/p>\n\n\n\n<p><strong>Word List <\/strong>= { \u201cbat\u201d, \u201cboy\u201d, \u201cbot\u201d, \u201cbog\u201d }<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"576\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/0-1024x576.png\" alt=\"Example of word ladder\n\" class=\"wp-image-347\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/0-1024x576.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/0-300x169.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/0-768x432.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/0-750x422.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/0-1140x641.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/0.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>The shortest word transformation from &#8220;rat&#8221; to &#8220;bog&#8221; in the given word list is 4, and the sequence is &#8220;rat&#8221; -&gt; &#8220;bat&#8221; -&gt; &#8220;bot&#8221; &#8211;&gt; &#8220;bog&#8221;. Note that the word &#8220;boy&#8221; was present in the word list but was not a valid transformation in this case.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>BFS Traversal Approach to Solve Word Ladder<\/strong><\/h2>\n\n\n\n<p><strong>The breadth-first search (BFS) approach is an efficient approach to solving the World Ladder problem. <\/strong>BFS explores all possible word transformations while keeping track of the shortest path to reach the ending word. The BFS algorithm starts with the starting word, explores its neighboring words, and continues the process until it reaches the ending word.<\/p>\n\n\n\n<p>Start with declaring a queue to store <a href=\"https:\/\/favtutor.com\/blogs\/breadth-first-search-java\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/blogs\/breadth-first-search-java\">BFS traversal<\/a> and a HashSet to check whether a new word was present in the word list or not. The hashset is used to reduce the time complexity.<\/p>\n\n\n\n<p>Let\u2019s understand it better with an example.<\/p>\n\n\n\n<p><strong>Step: 1<\/strong> Enqueue the start word &#8220;rat&#8221; with a transformation length of 1, and Initialise the word set to [&#8220;bat&#8221;, &#8220;boy&#8221;, &#8220;bot&#8221;, &#8220;bog&#8221;].<\/p>\n\n\n\n<p><strong>Step: 2<\/strong>  Dequeue &#8220;rat&#8221; (transformation length = 1). The key step involves generating one-letter transformations from the current word by changing the letter &#8220;r&#8221; to each letter from &#8216;a&#8217; to &#8216;z&#8217; and selecting words present in the word list.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"407\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/1-1-1-1024x407.png\" alt=\"Step:2 rat to bat\" class=\"wp-image-348\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/1-1-1-1024x407.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/1-1-1-300x119.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/1-1-1-768x306.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/1-1-1-750x298.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/1-1-1-1140x454.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/1-1-1.png 1244w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>Since \u201cbat\u201d is present in the list, we can transform \u201crat\u201d to \u201cbat\u201d.<\/p>\n\n\n\n<p>Now, Enqueue &#8220;bat&#8221; with a transformation length of 2, and mark &#8220;bat&#8221; as visited by removing it from the word set.<\/p>\n\n\n\n<p><strong>Step: 3<\/strong> Dequeue &#8220;bat&#8221; (transformation length = 2).<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"389\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/2-2-1024x389.png\" alt=\"step 3: bat to bot\n\" class=\"wp-image-349\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/2-2-1024x389.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/2-2-300x114.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/2-2-768x292.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/2-2-750x285.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/2-2-1140x433.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/2-2.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>Generate one-letter transformations: &#8220;bat&#8221; (ignore, as it&#8217;s the same as the current word), &#8220;bot&#8221;.&nbsp;<\/p>\n\n\n\n<p>Enqueue &#8220;bot&#8221; with a transformation length of 3, and mark &#8220;bot&#8221; as visited by removing it from the word set.<\/p>\n\n\n\n<p><strong>Step: 4 <\/strong>Dequeue &#8220;bot&#8221; (transformation length = 3).<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"450\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/3-2-1024x450.png\" alt=\"Step: 4 bot to bog\n\" class=\"wp-image-350\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/3-2-1024x450.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/3-2-300x132.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/3-2-768x337.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/3-2-750x329.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/3-2-1140x501.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/3-2.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>Generate one-letter transformations: &#8220;bot&#8221; (ignore), &#8220;bat&#8221; (ignore), &#8220;hot&#8221;, &#8230;, &#8220;bot&#8221; (ignore).<\/p>\n\n\n\n<p>Enqueue &#8220;bog&#8221; with a transformation length of 4. Mark &#8220;bog&#8221; as visited by removing it from the word set.<\/p>\n\n\n\n<p><strong>Step: 5 <\/strong>Dequeue &#8220;bog&#8221; (transformation length = 4).<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-large\"><img decoding=\"async\" width=\"1024\" height=\"293\" src=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/4-2-1024x293.png\" alt=\"Step: 5 bog: end word\" class=\"wp-image-351\" srcset=\"https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/4-2-1024x293.png 1024w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/4-2-300x86.png 300w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/4-2-768x220.png 768w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/4-2-750x214.png 750w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/4-2-1140x326.png 1140w, https:\/\/favtutor.com\/articles\/wp-content\/uploads\/2023\/11\/4-2.png 1280w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/figure>\n<\/div>\n\n\n<p>The target word &#8220;bog&#8221; is reached, and the transformation length is 4.<\/p>\n\n\n\n<p>Return the transformation length, which is 4.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the C++ program to solve the Word Ladder problem:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;queue&gt;\n#include &lt;unordered_set&gt;\n\nusing namespace std;\n\nclass Solution {\npublic:\n    int wordLadderLength(string startword, string targetword, vector&lt;string&gt;&amp; wordlist) {\n        queue&lt;pair&lt;string, int&gt;&gt; q;\n        q.push({startword, 1});\n\n        \/\/ Using an unordered_set for O(1) word existence check and removal\n        unordered_set&lt;string&gt; st(wordlist.begin(), wordlist.end());\n      \n      \t\/\/ Remove the start word from the set\n        st.erase(startword); \n\n        while (!q.empty()) {\n            string word = q.front().first;\n            int steps = q.front().second;\n            q.pop();\n\n            if (word == targetword) {\n                return steps;\n            }\n\n            \/\/ Generate one-letter transformations of the current word\n            for (int i = 0; i &lt; word.size(); i++) {\n                char original = word[i];\n\n                for (char ch = 'a'; ch &lt;= 'z'; ch++) {\n                    word[i] = ch;\n\n                    if (st.find(word) != st.end()) {\n                        \/\/ If the transformed word is in the set, remove it and enqueue\n                        st.erase(word);\n                        q.push({word, steps + 1});\n                    }\n                }\n\n                \/\/ Restore the original character at position I\n                word[i] = original;\n            }\n        }\n\t\t\n      \t\/\/ If no transformation found\n        return 0; \n    }\n};\n\nint main() {\n    Solution solution;\n    \n    string startWord = &quot;rat&quot;;\n    string endWord = &quot;bog&quot;;\n    vector&lt;string&gt; wordList = {&quot;bat&quot;, &quot;boy&quot;, &quot;bot&quot;, &quot;bog&quot;};\n\n    int result = solution.wordLadderLength(startWord, endWord, wordList);\n\n    if (result &gt; 0) {\n        cout &lt;&lt; &quot;Shortest word ladder length: &quot; &lt;&lt; result &lt;&lt; endl;\n    } \n  \telse {\n        cout &lt;&lt; &quot;No transformation sequence found.&quot; &lt;&lt; endl;\n    }\n\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Below is the Python program for the BFS approach to solve Word Ladder problem:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">from collections import deque\n\nclass Solution:\n    def word_ladder_length(self, start_word, target_word, word_list):\n        q = deque([(start_word, 1)])\n        st = set(word_list)\n        # Remove the start word from the set\n        st.discard(start_word)  \n\n        while q:\n            word, steps = q.popleft()\n\n            if word == target_word:\n                return steps\n\n            # Generate one-letter transformations of the current word\n            for i in range(len(word)):\n                original = word[i]\n                for ch in 'abcdefghijklmnopqrstuvwxyz':\n                  \t# Generate a new word\n                    new_word = word[:i] + ch + word[i+1:]  \n                    if new_word in st:\n                        # If the transformed word is in the set, remove it and enqueue\n                        st.remove(new_word)\n                        q.append((new_word, steps + 1))\n\n                # Restore the original character at position i\n                word = word[:i] + original + word[i+1:]\n                \n\t\t# If no transformation found\n        return 0  \n\n\nif __name__ == &quot;__main__&quot;:\n    solution = Solution()\n\n    start_word = &quot;rat&quot;\n    end_word = &quot;bog&quot;\n    word_list = [&quot;bat&quot;, &quot;boy&quot;, &quot;bot&quot;, &quot;bog&quot;]\n\n    result = solution.word_ladder_length(start_word, end_word, word_list)\n\n    if result &gt; 0:\n        print(&quot;Shortest word ladder length:&quot;, result)\n    else:\n        print(&quot;No transformation sequence found.&quot;)\n<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>You can the Java program below for Word Ladder:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">import java.util.*;\n\nclass Solution {\n    public int wordLadderLength(String startWord, String targetWord, List&lt;String&gt; wordList) {\n        Queue&lt;Map.Entry&lt;String, Integer&gt;&gt; q = new LinkedList&lt;&gt;();\n        q.offer(new AbstractMap.SimpleEntry&lt;&gt;(startWord, 1));\n\n        Set&lt;String&gt; wordSet = new HashSet&lt;&gt;(wordList);\n      \t\/\/ Remove the start word from the set\n        wordSet.remove(startWord); \n\n        while (!q.isEmpty()) {\n            Map.Entry&lt;String, Integer&gt; current = q.poll();\n            String word = current.getKey();\n            int steps = current.getValue();\n\n            if (word.equals(targetWord)) {\n                return steps;\n            }\n\n            \/\/ Generate one-letter transformations of the current word\n            for (int i = 0; i &lt; word.length(); i++) {\n                char[] chars = word.toCharArray();\n                char original = chars[i];\n\n                for (char ch = 'a'; ch &lt;= 'z'; ch++) {\n                    chars[i] = ch;\n                    String transformedWord = new String(chars);\n\n                    if (wordSet.contains(transformedWord)) {\n                        \/\/ If the transformed word is in the set, remove it and enqueue\n                        wordSet.remove(transformedWord);\n                        q.offer(new AbstractMap.SimpleEntry&lt;&gt;(transformedWord, steps + 1));\n                    }\n                }\n\n                \/\/ Restore the original character at position i\n                chars[i] = original;\n            }\n        }\n\t\t\/\/ If no transformation found\n        return 0; \n    }\n\n    public static void main(String[] args) {\n        Solution solution = new Solution();\n\n        String startWord = &quot;rat&quot;;\n        String endWord = &quot;bog&quot;;\n        List&lt;String&gt; wordList = Arrays.asList(&quot;bat&quot;, &quot;boy&quot;, &quot;bot&quot;, &quot;bog&quot;);\n\n        int result = solution.wordLadderLength(startWord, endWord, wordList);\n\n        if (result &gt; 0) {\n            System.out.println(&quot;Shortest word ladder length: &quot; + result);\n        } else {\n            System.out.println(&quot;No transformation sequence found.&quot;);\n        }\n    }\n}<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>Shortest word ladder length: 4<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Complexity Analysis<\/strong><\/h3>\n\n\n\n<p><strong>The time complexity of the Word Ladder solution is O(N * M * 26)<\/strong>, where N represents the size of the word list array, and M denotes the word length of the words present in the word list. It&#8217;s important to note that the constant factor 26 is attributed to the number of characters in the alphabet.<\/p>\n\n\n\n<p>The space complexity is O(N), encompassing the creation of an unordered set and the storage of all values from the wordList array. This space complexity accounts for the memory required for efficient traversal and storage during the execution of the algorithm.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>In summary, the Word Ladder problem is a creative challenge with practical applications in natural language processing, spell check and autocorrection systems, and genetic algorithms. We used the BFS traversal approach to solve this problem with the time complexity O(N * M * 26), where N is the size of the word list, and M is the word length.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Understand the word ladder programming problem from leetcode and get the solution in C++, Java, and Python.<\/p>\n","protected":false},"author":12,"featured_media":353,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[29,14,15],"class_list":["post-346","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-bfs","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/346","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=346"}],"version-history":[{"count":3,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/346\/revisions"}],"predecessor-version":[{"id":419,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/346\/revisions\/419"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/353"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=346"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=346"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=346"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}