Wd Ladd II Ld Pgamming Sluins | Ld Pblm Sluins in ++, Java, & Pyhn []

LeetCode Problem | LeetCode Problems For Beginners | LeetCode Problems & Solutions | Improve Problem Solving Skills | LeetCode Problems Java | LeetCode Solutions in C++

Hello Programmers/Coders, Today we are going to share solutions to the Programming problems of LeetCode Solutions in C++, Java, & Python. At Each Problem with Successful submission with all Test Cases Passed, you will get a score or marks and LeetCode Coins. And after solving maximum problems, you will be getting stars. This will highlight your profile to the recruiters.

In this post, you will find the solution for the Word Ladder II in C++, Java & Python-LeetCode problem. We are providing the correct and tested solutions to coding problems present on LeetCode. If you are not able to solve any problem, then you can take help from our Blog/website.

Use “Ctrl+F” To Find Any Questions Answer. & For Mobile User, You Just Need To Click On Three dots In Your Browser & You Will Get A “Find” Option There. Use These Option to Get Any Random Questions Answer.

About LeetCode

LeetCode is one of the most well-known online judge platforms to help you enhance your skills, expand your knowledge and prepare for technical interviews. 

LeetCode is for software engineers who are looking to practice technical questions and advance their skills. Mastering the questions in each level on LeetCode is a good way to prepare for technical interviews and keep your skills sharp. They also have a repository of solutions with the reasoning behind each step.

LeetCode has over 1,900 questions for you to practice, covering many different programming concepts. Every coding problem has a classification of either EasyMedium, or Hard.

LeetCode problems focus on algorithms and data structures. Here is some topic you can find problems on LeetCode:

  • Mathematics/Basic Logical Based Questions
  • Arrays
  • Strings
  • Hash Table
  • Dynamic Programming
  • Stack & Queue
  • Trees & Graphs
  • Greedy Algorithms
  • Breadth-First Search
  • Depth-First Search
  • Sorting & Searching
  • BST (Binary Search Tree)
  • Database
  • Linked List
  • Recursion, etc.

Leetcode has a huge number of test cases and questions from interviews too like Google, Amazon, Microsoft, Facebook, Adobe, Oracle, Linkedin, Goldman Sachs, etc. LeetCode helps you in getting a job in Top MNCs. To crack FAANG Companies, LeetCode problems can help you in building your logic.

Link for the ProblemWord Ladder II– LeetCode Problem

Word Ladder II– LeetCode Problem

Problem:

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 all the shortest transformation sequences from beginWord to endWord, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words [beginWord, s1, s2, ..., sk].

Example 1:

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: [["hit","hot","dot","dog","cog"],["hit","hot","lot","log","cog"]]
Explanation: There are 2 shortest transformation sequences:
"hit" -> "hot" -> "dot" -> "dog" -> "cog"
"hit" -> "hot" -> "lot" -> "log" -> "cog"

Example 2:

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

Constraints:

  • 1 <= beginWord.length <= 5
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 1000
  • wordList[i].length == beginWord.length
  • beginWordendWord, and wordList[i] consist of lowercase English letters.
  • beginWord != endWord
  • All the words in wordList are unique.
Word Ladder II– LeetCode Solutions
Word Ladder II Solution in C++:
class Solution {
 public:
  vector> findLadders(string beginWord, string endWord,
                                     vector& wordList) {
    vector> ans;
    unordered_set wordSet(begin(wordList), end(wordList));
    queue> paths{{{beginWord}}};  // {{"hit"}}

    while (!paths.empty()) {
      unordered_set currentLevelVisited;
      for (int size = paths.size(); size > 0; --size) {
        vector path = paths.front();
        paths.pop();                    // {"hit"}
        string lastWord = path.back();  // "hit"
        for (int i = 0; i < lastWord.length(); ++i) {
          char cache = lastWord[i];  // cache = 'i'
          for (char c = 'a'; c <= 'z'; ++c) {
            lastWord[i] = c;                // "hit" -> "hot" (temporarily)
            if (wordSet.count(lastWord)) {  // find "hot" in wordSet
              currentLevelVisited.insert(lastWord);  // mark "hot" as visited
              vector nextPath(path);
              nextPath.push_back(lastWord);  // nextPath = {"hit", "hot"}
              if (lastWord == endWord)
                ans.push_back(nextPath);
              else
                paths.push(nextPath);
            }
          }
          lastWord[i] = cache;  // "hot" back to "hit"
        }
      }
      for (const string& word : currentLevelVisited)
        wordSet.erase(word);
    }

    return ans;
  }
};
Word Ladder II Solution in Java:
class Solution {
  public List> findLadders(String beginWord, String endWord, List wordList) {
    Set wordSet = new HashSet<>(wordList);
    if (!wordSet.contains(endWord))
      return new ArrayList<>();

    Map> parentToChildren = new HashMap<>();
    Set currentLevelWords = new HashSet<>();
    currentLevelWords.add(beginWord);
    boolean isFound = false;

    while (!currentLevelWords.isEmpty()) {
      // remove words in current level
      for (final String word : currentLevelWords)
        wordSet.remove(word);
      Set nextLevelWords = new HashSet<>();
      // `parent` will be used as a key in `parentToChildren`
      for (final String parent : currentLevelWords) {
        StringBuilder sb = new StringBuilder(parent);
        for (int i = 0; i < sb.length(); ++i) {
          final char cache = sb.charAt(i);
          for (char c = 'a'; c <= 'z'; ++c) {
            sb.setCharAt(i, c);
            final String child = sb.toString();
            if (wordSet.contains(child)) {
              if (child.equals(endWord))
                isFound = true;
              nextLevelWords.add(child);
              parentToChildren.computeIfAbsent(parent, k -> new ArrayList<>()).add(child);
            }
          }
          sb.setCharAt(i, cache);
        }
        currentLevelWords = nextLevelWords;
      }
      if (isFound)
        break;
    }

    if (!isFound)
      return new ArrayList<>();

    List> ans = new ArrayList<>();
    List path = new ArrayList<>(Arrays.asList(beginWord));

    dfs(parentToChildren, beginWord, endWord, path, ans);

    return ans;
  }

  // construct the ans by `parentToChildren`
  private void dfs(Map> parentToChildren, final String word,
                   final String endWord, List path, List> ans) {
    if (word.equals(endWord)) {
      ans.add(new ArrayList<>(path));
      return;
    }
    if (!parentToChildren.containsKey(word))
      return;

    for (final String child : parentToChildren.get(word)) {
      path.add(child);
      dfs(parentToChildren, child, endWord, path, ans);
      path.remove(path.size() - 1);
    }
  }
}
Word Ladder II Solution in Python:
class Solution:
  def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]:
    def dfs(word: str, path: List[str]) -> None:
      if word == endWord:
        ans.append(path)
        return
      if word not in dict:
        return

      for child in dict[word]:
        dfs(child, path + [child])

    ans = []
    wordList = set(wordList)

    if endWord not in wordList:
      return ans

    set1 = set([beginWord])
    dict = defaultdict(list)
    isFound = False

    while set1 and not isFound:
      for word in set1:
        wordList.discard(word)
      tempSet = set()
      for parent in set1:
        for i in range(len(parent)):
          for j in string.ascii_lowercase:
            newWord = parent[:i] + j + parent[i + 1:]
            if newWord == endWord:
              dict[parent].append(newWord)
              isFound = True
            elif newWord in wordList and not isFound:
              tempSet.add(newWord)
              dict[parent].append(newWord)
      set1 = tempSet

    if isFound:
      dfs(beginWord, [beginWord])

    return ans

Leave a Comment

Scroll to Top