Word Ladder LeetCode Solution

Last updated on July 20th, 2024 at 04:20 am

Here, We see Word Ladder LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Breadth-First Search

Companies

Amazon, Facebook, LinkedIn, Snapchat, Yelp

Level of Question

Hard

Word Ladder LeetCode Solution

Word Ladder LeetCode Solution

Problem Statement

transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s1 -> s2 -> ... -> sk such that:

  • Every adjacent pair of words differs by a single letter.
  • Every si for 1 <= i <= k is in wordList. Note that beginWord does not need to be in wordList.
  • sk == endWord

Given two words, beginWord and endWord, and a dictionary wordList, return the number of words in the shortest transformation sequence from beginWord to endWord, or 0 if no such sequence exists.

Example 1:
Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,”dot”,”dog”,”lot”,”log”,”cog”]
Output: 5
Explanation: One shortest transformation sequence is “hit” -> “hot” -> “dot” -> “dog” -> cog”, which is 5 words long.

Example 2:
Input: beginWord = “hit”, endWord = “cog”, wordList = [“hot”,”dot”,”dog”,”lot”,”log”]
Output: 0
Explanation: The endWord “cog” is not in wordList, therefore there is no valid transformation sequence.

1. Word Ladder LeetCode Solution C++

class Solution {
public:
    int ladderLength(string beginWord, string endWord, vector&lt;string&gt;&amp; wordList) {
        unordered_set&lt;string&gt; dict(wordList.begin(), wordList.end());
        queue&lt;string&gt; todo;
        todo.push(beginWord);
        int ladder = 1;
        while (!todo.empty()) {
            int n = todo.size();
            for (int i = 0; i &lt; n; i++) {
                string word = todo.front();
                todo.pop();
                if (word == endWord) {
                    return ladder;
                }
                dict.erase(word);
                for (int j = 0; j &lt; word.size(); j++) {
                    char c = word[j];
                    for (int k = 0; k &lt; 26; k++) {
                        word[j] = 'a' + k;
                        if (dict.find(word) != dict.end()) {
                            todo.push(word);
                        }
                     }
                    word[j] = c;
                }
            }
            ladder++;
        }
        return 0;
    }
};

2. Word Ladder LeetCode Solution Java

class Solution {
    public int ladderLength(String beginWord, String endWord, List&lt;String&gt; wordList) {
        if (!wordList.contains(endWord)) {
            return 0;
        }
        Set&lt;String&gt; dict = new HashSet&lt;&gt;(wordList);
        Set&lt;String&gt; beginSet = new HashSet&lt;&gt;();
        Set&lt;String&gt; endSet = new HashSet&lt;&gt;();
        beginSet.add(beginWord);
        endSet.add(endWord);
        int step = 1;
        Set&lt;String&gt; visited = new HashSet&lt;&gt;();
        while (!beginSet.isEmpty() &amp;&amp; !endSet.isEmpty()) {
            if (beginSet.size() &gt; endSet.size()) {
                Set&lt;String&gt; set = beginSet;
                beginSet = endSet;
                endSet = set;
            }
            Set&lt;String&gt; temp = new HashSet&lt;&gt;();
            for (String word : beginSet) {
                char[] chs = word.toCharArray();
                for (int i = 0; i &lt; chs.length; i++) {
                    for (char c = 'a'; c &lt;= 'z'; c++) {
                        char old = chs[i];
                        chs[i] = c;
                        String target = String.valueOf(chs);
                        if (endSet.contains(target)) {
                            return step + 1;
                        }
                        if (!visited.contains(target) &amp;&amp; dict.contains(target)) {
                            temp.add(target);
                            visited.add(target);
                        }
                        chs[i] = old;
                    }
                }
            }
            beginSet = temp;
            step++;
        }
        return 0;
    }
}

3. Word Ladder Solution JavaScript

var ladderLength = function(beginWord, endWord, wordList) {
    const wordSet = new Set(wordList)
    let queue = [beginWord];
    let steps = 1;
    while(queue.length) {
        const next = [];
        for(let word of queue) {
            if(word === endWord) return steps;
            for(let i = 0; i &lt; word.length; i++) {
                for(let j = 0; j &lt; 26; j++) {
                    const newWord = word.slice(0, i) + String.fromCharCode(j + 97) + word.slice(i+1);
                    if(wordSet.has(newWord)) {
                        next.push(newWord);
                        wordSet.delete(newWord);
                    }
                }
            }
        }
        queue = next
        steps++;
    }
    return 0;    
};

4. Word Ladder Solution Python

class Solution(object):
    def ladderLength(self, beginWord, endWord, wordDict):
        if endWord not in wordDict:
            return 0
        length = 2
        front, back = set([beginWord]), set([endWord])
        wordDict = set(wordDict)
        wordDict.discard(beginWord)
        while front:
            front = wordDict &amp; (set(word[:index] + ch + word[index+1:] for word in front 
                                for index in range(len(beginWord)) for ch in string.ascii_lowercase))
            if front &amp; back:
                return length
            length += 1
            if len(front) &gt; len(back):
                front, back = back, front
            wordDict -= front
        return 0
Scroll to Top