Word Ladder
Explore how to apply breadth-first search to solve the Word Ladder problem by finding the shortest path transforming one word into another. Understand problem constraints and build a clear approach to tackle similar coding interview challenges using BFS.
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 can 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 the
words. Thesrcdoes not need to be present inwords.
Constraints:
-
src.length -
src.lengthdest.lengthwords[i].length -
srcdest -
words.length -
No duplicates in the
words -
src,dest, andwords[i]consist of lowercase English characters.
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Word Ladder
What’s the correct output for the following inputs?
src = “hit”
dest = “cog”
words = [“log”, “dot”, “lot”, “dog”, “hot”, “cog”]
5
6
0
7
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Try it yourself
Implement your solution in main.js in the following coding playground. We have provided a useful code template in the other file that you may build on to solve this problem.
import Queue from "./queue.js";function wordLadder(src, dest, words) {// Replace this placeholder return statement with your codereturn -1;}export { wordLadder };