Tutorialspoint
Problem
Solution
Submissions

Word Ladder

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C# program to implement the LadderLength(string beginWord, string endWord, List<string> wordList) function, which returns the length of the shortest transformation sequence from beginWord to endWord, such that: 1. Only one letter can be changed at a time. 2. Each transformed word must exist in the word list. 3. Return 0 if there is no such transformation sequence. All words have the same length and contain only lowercase alphabetic characters.

Example 1
  • Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
  • Output: 5
  • Explanation:
    • One shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog", with a length of 5.
Example 2
  • Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
  • Output: 0
  • Explanation:
    • The endWord "cog" is not in the wordList, so no transformation sequence exists.
Constraints
  • 1 ≤ beginWord.length ≤ 10
  • endWord.length == beginWord.length
  • 1 ≤ wordList.length ≤ 5000
  • All strings consist of lowercase English letters
  • All words in wordList are unique
  • Time Complexity: O(N * M^2) where N is the number of words and M is the word length
  • Space Complexity: O(N * M)
QueueAlgorithmsSnowflakeTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a breadth-first search (BFS) approach to find the shortest path
  • Create a set from the word list for O(1) lookups
  • Use a queue to implement BFS and track the level (number of transformations)
  • For each word, try changing each character and check if the new word is in the wordList
  • Mark words as visited to avoid cycles

Steps to solve by this approach:

 Step 1: Convert the wordList to a HashSet for O(1) lookups and check if endWord exists in it.
 Step 2: Initialize a queue for BFS and a set to track visited words.
 Step 3: Start BFS by adding the beginWord to the queue with level 1.
 Step 4: For each word in the queue, try changing each character to all possible letters.
 Step 5: Check if the new word exists in the wordList and hasn't been visited.
 Step 6: If the new word matches the endWord, return the current level + 1.
 Step 7: Add valid new words to the queue with an incremented level and mark them as visited.

Submitted Code :