Word Ladder LeetCode Programming Solutions | LeetCode Problem Solutions in C++, Java, & Python [💯Correct]

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 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– LeetCode Problem

Word Ladder– 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 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.

Constraints:

  • 1 <= beginWord.length <= 10
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 5000
  • 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– LeetCode Solutions
Word Ladder Solution in C++:
class Solution {
 public:
  int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
    unordered_set<string> wordSet(begin(wordList), end(wordList));
    if (!wordSet.count(endWord))
      return 0;

    int ans = 0;
    queue<string> q{{beginWord}};

    while (!q.empty()) {
      ++ans;
      for (int size = q.size(); size > 0; --size) {
        string word = q.front();
        q.pop();
        for (int i = 0; i < word.length(); ++i) {
          const char cache = word[i];
          for (char c = 'a'; c <= 'z'; ++c) {
            word[i] = c;
            if (word == endWord)
              return ans + 1;
            if (wordSet.count(word)) {
              q.push(word);
              wordSet.erase(word);
            }
          }
          word[i] = cache;
        }
      }
    }

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

    int ans = 0;
    Queue<String> q = new LinkedList<>(Arrays.asList(beginWord));

    while (!q.isEmpty()) {
      ++ans;
      for (int size = q.size(); size > 0; --size) {
        StringBuilder sb = new StringBuilder(q.poll());
        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 word = sb.toString();
            if (word.equals(endWord))
              return ans + 1;
            if (wordSet.contains(word)) {
              q.offer(word);
              wordSet.remove(word);
            }
          }
          sb.setCharAt(i, cache);
        }
      }
    }

    return 0;
  }
}
Word Ladder Solution in Python:
class Solution:
  def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
    wordSet = set(wordList)
    if endWord not in wordSet:
      return 0

    ans = 0
    q = deque([beginWord])

    while q:
      ans += 1
      for _ in range(len(q)):
        wordList = list(q.popleft())
        for i, cache in enumerate(wordList):
          for c in string.ascii_lowercase:
            wordList[i] = c
            word = ''.join(wordList)
            if word == endWord:
              return ans + 1
            if word in wordSet:
              q.append(word)
              wordSet.remove(word)
          wordList[i] = cache

    return 0

Leave a Comment

Ads Blocker Image Powered by Code Help Pro
Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Refresh
Powered By
CHP Adblock Detector Plugin | Codehelppro