Solution: Word Ladder
Let's solve the Word Ladder problem using the Tree Breadth-first Search pattern.
We'll cover the following
Statement
Given two words, src
and dest
, and a list, words
, return the number of words in the shortest transformation sequence from src
to dest
. If no such sequence could be formed, return .
A transformation sequence is a sequence of words src
that has the following properties:
-
dest
- Every pair of consecutive words differs by a single character.
- All the words in the sequence are present in
words
. Thesrc
does not need to be present inwords
.
Constraints:
-
src.length
-
src.length
dest.length
words[i].length
-
src
dest
-
words.length
-
No duplicates in
words
-
src
,dest
, andwords[i]
consist of lowercase English characters.
Solution
We will find the shortest transformation sequence using the BFS approach. We will create a set of words for faster lookup of available words, a queue to store the words that need to be checked for the transformation sequence through BFS, and a counter, length
, to store the length of the sequence.
We start by pushing the src
word into the queue. After that, we follow the steps given below:
-
Pop a word from the queue and store it in
curr
. -
Check all the words in the set that only differ by one character from
curr
.- Push all such words into the queue and remove them from the set.
-
Keep popping the first word from the queue into
curr
and finding all the adjacent words ofcurr
that differ by only one character until we have traversed all the words or have not found thedest
. -
In each iteration, the
length
is incremented since each iteration checks all adjacent words (i.e., the words that differ by one character) of the popped word. Oncedest
is found, we returnlength + 1
, representing the length of the sequence. We add while returning thelength
to countdest
in the length of the shortest transformation sequence.
Let’s look at an example below:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.