{"id":183,"date":"2025-05-27T17:59:48","date_gmt":"2025-05-27T12:29:48","guid":{"rendered":"https:\/\/codeanddebug.in\/blog\/?p=183"},"modified":"2025-05-31T18:56:34","modified_gmt":"2025-05-31T13:26:34","slug":"word-ladder-leetcode-127","status":"publish","type":"post","link":"https:\/\/codeanddebug.in\/blog\/word-ladder-leetcode-127\/","title":{"rendered":"Word Ladder | Leetcode 127 | Explained using BFS"},"content":{"rendered":"\n<p>Learn how to solve the <strong>Word Ladder<\/strong> problem by building a <strong>BFS <\/strong>over words, changing one letter at a time. This clear, line-by-line guide uses simple code comments and a dry run to show how we get the shortest transformation length.<\/p>\n\n\n\n<p>Here&#8217;s the [<strong><a href=\"https:\/\/leetcode.com\/problems\/word-ladder\/description\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Problem Link<\/span><\/mark><\/a><\/strong>] to begin with.<\/p>\n\n\n<div style=\"max-width: -moz-fit-content; \" class=\"wp-block-ub-table-of-contents-block ub_table-of-contents ub_table-of-contents-collapsed\" id=\"ub_table-of-contents-1aa1f12c-1b4d-4c3b-8d9e-df4d95cef9e8\" data-linktodivider=\"false\" data-showtext=\"show\" data-hidetext=\"hide\" data-scrolltype=\"auto\" data-enablesmoothscroll=\"true\" data-initiallyhideonmobile=\"false\" data-initiallyshow=\"false\"><div class=\"ub_table-of-contents-header-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-header\" style=\"text-align: left; \">\n\t\t\t\t<div class=\"ub_table-of-contents-title\">Contents:<\/div>\n\t\t\t\t<div class=\"ub_table-of-contents-header-toggle\">\n\t\t\t<div class=\"ub_table-of-contents-toggle\" style=\"\">\n\t\t\t\u00a0[<a class=\"ub_table-of-contents-toggle-link\" href=\"#\" style=\"\">show<\/a>]\n\t\t\t<\/div>\n\t\t<\/div>\n\t\t\t<\/div>\n\t\t<\/div><div class=\"ub_table-of-contents-extra-container\" style=\"\">\n\t\t\t<div class=\"ub_table-of-contents-container ub_table-of-contents-1-column ub-hide\">\n\t\t\t\t<ul style=\"\"><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/word-ladder-leetcode-127\/#0-what-the-problem-asks\" style=\"\">What the Problem Asks<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/word-ladder-leetcode-127\/#1-intuition-amp-approach\" style=\"\">Intuition &amp; Approach<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/word-ladder-leetcode-127\/#2-code-implementation-with-comments\" style=\"\">Code Implementation (with Comments)<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/word-ladder-leetcode-127\/#3-step-by-step-explanation\" style=\"\">Step-by-Step Explanation<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/word-ladder-leetcode-127\/#4-dry-run-example\" style=\"\">Dry Run Example<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/word-ladder-leetcode-127\/#5-time-amp-space-complexity\" style=\"\">Time &amp; Space Complexity<\/a><\/li><li style=\"\"><a href=\"https:\/\/codeanddebug.in\/blog\/word-ladder-leetcode-127\/#6-conclusion\" style=\"\">Conclusion<\/a><\/li><\/ul>\n\t\t\t<\/div>\n\t\t<\/div><\/div>\n\n\n<h2 class=\"wp-block-heading\" id=\"0-what-the-problem-asks\">What the Problem Asks<\/h2>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>You have a <strong>beginWord<\/strong>, an <strong>endWord<\/strong>, and a list of allowed words (<strong>wordList<\/strong>).<br>You can change one letter at a time, but each intermediate word <strong>must<\/strong> be in the word list.<br>Return the <strong>fewest steps<\/strong> needed to go from <code>beginWord<\/code> to <code>endWord<\/code>. If it\u2019s impossible, return <code>0<\/code>.<\/p>\n<\/blockquote>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><em>Also read about the Python Program to <strong><a href=\"https:\/\/codeanddebug.in\/blog\/python-program-print-divisors-factors-integer\/\" target=\"_blank\" rel=\"noreferrer noopener\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-purple-color\"><span style=\"text-decoration: underline;\">Solve Word Ladder &#8211; 2<\/span><\/mark><\/a><\/strong><\/em>.<\/p>\n<\/blockquote>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"1-intuition-amp-approach\">Intuition &amp; Approach<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Breadth-First Search (BFS):<\/strong>\n<ul class=\"wp-block-list\">\n<li>We treat each word as a node in a graph.<\/li>\n\n\n\n<li>There\u2019s an edge between two words if they differ by exactly one letter.<\/li>\n\n\n\n<li>BFS from <code>beginWord<\/code> will find the shortest path to <code>endWord<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Word Set for Fast Lookups:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Convert <code>wordList<\/code> to a set so we can check existence in O(1).<\/li>\n\n\n\n<li>Remove words from the set when we visit them to avoid revisiting.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Level Tracking:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Each BFS queue entry holds <code>(currentWord, stepsSoFar)<\/code>.<\/li>\n\n\n\n<li>When we reach <code>endWord<\/code>, <code>stepsSoFar<\/code> is the answer.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"2-code-implementation-with-comments\">Code Implementation (with Comments)<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"from collections import deque\n\nclass Solution:\n    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -&gt; int:\n        # 1. Put all allowed words into a set for O(1) lookups.\n        wordSet = set(wordList)\n        # If endWord isn't in the list, we can never reach it.\n        if endWord not in wordSet:\n            return 0\n\n        # 2. Initialize BFS queue with (beginWord, stepCount=1).\n        queue = deque()\n        queue.append((beginWord, 1))\n\n        # 3. Standard BFS loop\n        while queue:\n            curr_word, level = queue.popleft()\n            # If we've reached the end, return the number of steps.\n            if curr_word == endWord:\n                return level\n\n            # 4. Try changing each letter in curr_word\n            for i in range(len(curr_word)):\n                # For each position, try all possible lowercase letters\n                for ch in &quot;abcdefghijklmnopqrstuvwxyz&quot;:\n                    # Skip if the letter is the same\n                    if ch == curr_word[i]:\n                        continue\n                    # Form a new word by replacing the i-th letter\n                    new_word = curr_word[:i] + ch + curr_word[i+1:]\n                    # If the new word is in our set, it's a valid step\n                    if new_word in wordSet:\n                        # Add it to the queue with stepCount + 1\n                        queue.append((new_word, level + 1))\n                        # Remove from set so we don't visit again\n                        wordSet.remove(new_word)\n\n        # If queue empties without finding endWord, there's no path\n        return 0\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #C586C0\">from<\/span><span style=\"color: #D4D4D4\"> collections <\/span><span style=\"color: #C586C0\">import<\/span><span style=\"color: #D4D4D4\"> deque<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #569CD6\">class<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #4EC9B0\">Solution<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">    <\/span><span style=\"color: #569CD6\">def<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">ladderLength<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #9CDCFE\">self<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">beginWord<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">endWord<\/span><span style=\"color: #D4D4D4\">: <\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">, <\/span><span style=\"color: #9CDCFE\">wordList<\/span><span style=\"color: #D4D4D4\">: List[<\/span><span style=\"color: #4EC9B0\">str<\/span><span style=\"color: #D4D4D4\">]) -&gt; <\/span><span style=\"color: #4EC9B0\">int<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># 1. Put all allowed words into a set for O(1) lookups.<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        wordSet = <\/span><span style=\"color: #4EC9B0\">set<\/span><span style=\"color: #D4D4D4\">(wordList)<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># If endWord isn&#39;t in the list, we can never reach it.<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> endWord <\/span><span style=\"color: #569CD6\">not<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #569CD6\">in<\/span><span style=\"color: #D4D4D4\"> wordSet:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># 2. Initialize BFS queue with (beginWord, stepCount=1).<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        queue = deque()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        queue.append((beginWord, <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># 3. Standard BFS loop<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">while<\/span><span style=\"color: #D4D4D4\"> queue:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            curr_word, level = queue.popleft()<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># If we&#39;ve reached the end, return the number of steps.<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> curr_word == endWord:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> level<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #6A9955\"># 4. Try changing each letter in curr_word<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">            <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> i <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #DCDCAA\">range<\/span><span style=\"color: #D4D4D4\">(<\/span><span style=\"color: #DCDCAA\">len<\/span><span style=\"color: #D4D4D4\">(curr_word)):<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #6A9955\"># For each position, try all possible lowercase letters<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                <\/span><span style=\"color: #C586C0\">for<\/span><span style=\"color: #D4D4D4\"> ch <\/span><span style=\"color: #C586C0\">in<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #CE9178\">&quot;abcdefghijklmnopqrstuvwxyz&quot;<\/span><span style=\"color: #D4D4D4\">:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #6A9955\"># Skip if the letter is the same<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> ch == curr_word[i]:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        <\/span><span style=\"color: #C586C0\">continue<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #6A9955\"># Form a new word by replacing the i-th letter<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    new_word = curr_word[:i] + ch + curr_word[i+<\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">:]<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #6A9955\"># If the new word is in our set, it&#39;s a valid step<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                    <\/span><span style=\"color: #C586C0\">if<\/span><span style=\"color: #D4D4D4\"> new_word <\/span><span style=\"color: #569CD6\">in<\/span><span style=\"color: #D4D4D4\"> wordSet:<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        <\/span><span style=\"color: #6A9955\"># Add it to the queue with stepCount + 1<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        queue.append((new_word, level + <\/span><span style=\"color: #B5CEA8\">1<\/span><span style=\"color: #D4D4D4\">))<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        <\/span><span style=\"color: #6A9955\"># Remove from set so we don&#39;t visit again<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">                        wordSet.remove(new_word)<\/span><\/span>\n<span class=\"line\"><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #6A9955\"># If queue empties without finding endWord, there&#39;s no path<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">        <\/span><span style=\"color: #C586C0\">return<\/span><span style=\"color: #D4D4D4\"> <\/span><span style=\"color: #B5CEA8\">0<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"3-step-by-step-explanation\">Step-by-Step Explanation<\/h2>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Build <code>wordSet<\/code>:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Helps us quickly check if a transformed word is allowed.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>BFS Queue:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Starts with the <code>beginWord<\/code> at step <code>1<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>While Loop:<\/strong>\n<ul class=\"wp-block-list\">\n<li>Pop the front word and its current step count.<\/li>\n\n\n\n<li>If it matches <code>endWord<\/code>, we\u2019re done.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Generate Neighbors:<\/strong>\n<ul class=\"wp-block-list\">\n<li>For each position in <code>curr_word<\/code>, try replacing it with every letter <code>a\u2013z<\/code>.<\/li>\n\n\n\n<li>If the resulting <code>new_word<\/code> is in <code>wordSet<\/code>, it\u2019s a valid move:\n<ul class=\"wp-block-list\">\n<li>Enqueue <code>(new_word, level+1)<\/code>.<\/li>\n\n\n\n<li>Remove <code>new_word<\/code> from <code>wordSet<\/code> so we don\u2019t revisit it.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>No Path Found:<\/strong>\n<ul class=\"wp-block-list\">\n<li>If BFS completes without hitting <code>endWord<\/code>, return <code>0<\/code>.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"4-dry-run-example\">Dry Run Example<\/h2>\n\n\n\n<div class=\"wp-block-kevinbatdorf-code-block-pro\" data-code-block-pro-font-family=\"Code-Pro-JetBrains-Mono\" style=\"font-size:.875rem;font-family:Code-Pro-JetBrains-Mono,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;line-height:1.25rem;--cbp-tab-width:2;tab-size:var(--cbp-tab-width, 2)\"><span style=\"display:block;padding:16px 0 0 16px;margin-bottom:-1px;width:100%;text-align:left;background-color:#1E1E1E\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"54\" height=\"14\" viewBox=\"0 0 54 14\"><g fill=\"none\" fill-rule=\"evenodd\" transform=\"translate(1 1)\"><circle cx=\"6\" cy=\"6\" r=\"6\" fill=\"#FF5F56\" stroke=\"#E0443E\" stroke-width=\".5\"><\/circle><circle cx=\"26\" cy=\"6\" r=\"6\" fill=\"#FFBD2E\" stroke=\"#DEA123\" stroke-width=\".5\"><\/circle><circle cx=\"46\" cy=\"6\" r=\"6\" fill=\"#27C93F\" stroke=\"#1AAB29\" stroke-width=\".5\"><\/circle><\/g><\/svg><\/span><span role=\"button\" tabindex=\"0\" data-code=\"beginWord = &quot;hit&quot;\nendWord   = &quot;cog&quot;\nwordList  = [&quot;hot&quot;,&quot;dot&quot;,&quot;dog&quot;,&quot;lot&quot;,&quot;log&quot;,&quot;cog&quot;]\" style=\"color:#D4D4D4;display:none\" aria-label=\"Copy\" class=\"code-block-pro-copy-button\"><svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" style=\"width:24px;height:24px\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\"><path class=\"with-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4\"><\/path><path class=\"without-check\" stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2\"><\/path><\/svg><\/span><pre class=\"shiki dark-plus\" style=\"background-color: #1E1E1E\" tabindex=\"0\"><code><span class=\"line\"><span style=\"color: #D4D4D4\">beginWord = <\/span><span style=\"color: #CE9178\">&quot;hit&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">endWord   = <\/span><span style=\"color: #CE9178\">&quot;cog&quot;<\/span><\/span>\n<span class=\"line\"><span style=\"color: #D4D4D4\">wordList  = [<\/span><span style=\"color: #CE9178\">&quot;hot&quot;<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #CE9178\">&quot;dot&quot;<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #CE9178\">&quot;dog&quot;<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #CE9178\">&quot;lot&quot;<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #CE9178\">&quot;log&quot;<\/span><span style=\"color: #D4D4D4\">,<\/span><span style=\"color: #CE9178\">&quot;cog&quot;<\/span><span style=\"color: #D4D4D4\">]<\/span><\/span><\/code><\/pre><\/div>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 1:<\/strong> queue = [(&#8220;hit&#8221;,1)], wordSet={&#8220;hot&#8221;,&#8221;dot&#8221;,&#8221;dog&#8221;,&#8221;lot&#8221;,&#8221;log&#8221;,&#8221;cog&#8221;}<\/li>\n\n\n\n<li><strong>Step 2:<\/strong> pop (&#8220;hit&#8221;,1). Generate neighbors:\n<ul class=\"wp-block-list\">\n<li>&#8220;hot&#8221; is valid \u2192 enqueue (&#8220;hot&#8221;,2), remove &#8220;hot&#8221;.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Step 3:<\/strong> pop (&#8220;hot&#8221;,2). Neighbors:\n<ul class=\"wp-block-list\">\n<li>&#8220;dot&#8221; \u2192 enqueue (&#8220;dot&#8221;,3), remove &#8220;dot&#8221;.<\/li>\n\n\n\n<li>&#8220;lot&#8221; \u2192 enqueue (&#8220;lot&#8221;,3), remove &#8220;lot&#8221;.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Step 4:<\/strong> pop (&#8220;dot&#8221;,3):\n<ul class=\"wp-block-list\">\n<li>&#8220;dog&#8221; \u2192 enqueue (&#8220;dog&#8221;,4), remove &#8220;dog&#8221;.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Step 5:<\/strong> pop (&#8220;lot&#8221;,3):\n<ul class=\"wp-block-list\">\n<li>&#8220;log&#8221; \u2192 enqueue (&#8220;log&#8221;,4), remove &#8220;log&#8221;.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Step 6:<\/strong> pop (&#8220;dog&#8221;,4):\n<ul class=\"wp-block-list\">\n<li>&#8220;cog&#8221; \u2192 enqueue (&#8220;cog&#8221;,5), remove &#8220;cog&#8221;.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Step 7:<\/strong> pop (&#8220;log&#8221;,4): also can reach &#8220;cog&#8221;, but it\u2019s already removed.<\/li>\n\n\n\n<li><strong>Step 8:<\/strong> pop (&#8220;cog&#8221;,5): matches endWord \u2192 return 5.<\/li>\n<\/ul>\n\n\n\n<p>Result is <strong>5<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"5-time-amp-space-complexity\">Time &amp; Space Complexity<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time Complexity:<\/strong>\n<ul class=\"wp-block-list\">\n<li>In the worst case, for each of N words and each word of length L, we try 26 replacements: O(N \u00d7 L \u00d7 26).<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Space Complexity:<\/strong>\n<ul class=\"wp-block-list\">\n<li>O(N) for the <code>wordSet<\/code> and O(N) for the BFS queue in the worst case.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"6-conclusion\">Conclusion<\/h2>\n\n\n\n<p>By treating each word as a node and valid one-letter changes as edges, BFS finds the shortest transformation path in the fewest steps. The key tricks are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Using a <strong>set<\/strong> for fast lookups and removals.<\/li>\n\n\n\n<li>Enqueuing <code>(word, steps)<\/code> for level tracking.<\/li>\n\n\n\n<li>Removing words from <code>wordSet<\/code> as soon as they\u2019re visited.<\/li>\n<\/ul>\n\n\n\n<p>With this pattern, you can tackle many \u201cword transformation\u201d challenges in coding interviews. Happy coding!<\/p>\n\n\n\n<div class=\"wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-16018d1d wp-block-buttons-is-layout-flex\">\n<div class=\"wp-block-button\"><a class=\"wp-block-button__link wp-element-button\" href=\"https:\/\/www.codeanddebug.in\/course\/zero-to-hero-python-dsa\" target=\"_blank\" rel=\"noreferrer noopener\">Join our Advance DSA COURSE<\/a><\/div>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><em>For any changes to the article, kindly email at <a href=\"mailto:code@codeanddebug.in\">code@codeanddebug.in<\/a> or contact us at <a href=\"tel:+91-9712928220\">+91-9712928220<\/a>.<\/em><\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to solve the Word Ladder problem by building a BFS over words, changing one letter at a time. This clear, line-by-line guide uses simple code comments and a dry run to show how we get the shortest transformation length. Here&#8217;s the [Problem Link] to begin with. What the Problem Asks You have a<\/p>\n","protected":false},"author":1,"featured_media":184,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3,5],"tags":[17,18],"class_list":{"0":"post-183","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-data-structures-and-algorithm","8":"category-expert","9":"tag-graph","10":"tag-hard"},"featured_image_src":"https:\/\/codeanddebug.in\/blog\/wp-content\/uploads\/2025\/05\/word-ladder-1-featured-image.png","author_info":{"display_name":"codeanddebug","author_link":"https:\/\/codeanddebug.in\/blog\/author\/codeanddebug\/"},"_links":{"self":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/183","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/comments?post=183"}],"version-history":[{"count":3,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/183\/revisions"}],"predecessor-version":[{"id":234,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/posts\/183\/revisions\/234"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media\/184"}],"wp:attachment":[{"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/media?parent=183"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/categories?post=183"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codeanddebug.in\/blog\/wp-json\/wp\/v2\/tags?post=183"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}