Skip to main content

Word Ladder

KANISHKA GUPTA
EditReport

Description:​

A 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 sis_i for 1≤i≤k1 \le i \le k is in wordList. Note that beginWord does not need to be in wordList.
  • sk==endWords_k == 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.


Video Solution:​


Approaches:​

1. Breadth-First Search (BFS) (Optimal)​

Since we are looking for the shortest transformation sequence from a starting state to a target state, Breadth-First Search (BFS) is the ideal algorithm. We can treat each word as a node in a graph, and an edge exists between two words if they differ by exactly one character.

Algorithm:

  1. Hash Set for O(1)O(1) Lookups: Convert the given wordList into a Hash Set. This allows us to quickly check if a newly formed word exists in our dictionary. If endWord is not in this set, we can immediately return 0.
  2. Queue for BFS: Initialize a queue that stores the current word and the current sequence length (steps). Start by pushing (beginWord, 1).
  3. Explore Level by Level:
    • Pop a word from the queue. If it matches endWord, return the current step count.
    • For every character in the current word, replace it with all possible lowercase English letters ('a' to 'z').
    • If the newly formed word exists in our Hash Set, it is a valid transformation.
    • Crucial Step: Remove this new word from the Hash Set so we don't visit it again (which would cause infinite loops and unnecessary processing), and push it into the queue with steps + 1.
  4. If the queue becomes empty and we haven't reached the endWord, return 0.

Complexity​

  • Time Complexity: O(N×M×26)O(N \times M \times 26) where NN is the number of words in wordList and MM is the length of each word. For each word we process, we loop MM times, and within that loop, we substitute 26 characters. String manipulation and hashing take O(M)O(M) time. Thus, strictly speaking, it's O(N×M2)O(N \times M^2).
  • Space Complexity: O(N×M)O(N \times M) to store all the words in the Hash Set and the BFS Queue.

Solutions​

class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
unordered_set<string> wordSet(wordList.begin(), wordList.end());

// If the target word is not in the dictionary, no valid sequence exists
if (wordSet.find(endWord) == wordSet.end()) return 0;

queue<pair<string, int>> q;
q.push({beginWord, 1});

while (!q.empty()) {
string word = q.front().first;
int steps = q.front().second;
q.pop();

// If we reach the target word
if (word == endWord) return steps;

// Try changing every character to 'a'-'z'
for (int i = 0; i < word.size(); i++) {
char original = word[i];
for (char ch = 'a'; ch <= 'z'; ch++) {
word[i] = ch;

// If the new word exists in the dictionary
if (wordSet.find(word) != wordSet.end()) {
wordSet.erase(word); // Remove to avoid revisiting
q.push({word, steps + 1});
}
}
// Backtrack to the original character
word[i] = original;
}
}
return 0;
}
};
Track Your Progress

Done with this topic? Mark it as complete to track your progress.