Word Ladder
Explore how to use breadth-first search to solve the Word Ladder problem by finding the shortest transformation sequence between two words. Understand the problem constraints and learn to implement an efficient solution that checks single-character differences and sequences from a given word list.
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 the following coding playground.
#include <iostream>#include <vector>int WordLadder(std::string src, std::string dest, const std::vector<std::string>& words) {// Replace this placeholder return statement with your codereturn -1;}