Skip to content
BytePatterns

Word Ladder Steps

HardGraphs#bfs#shortest-path~45m

Problem

Given a starting word, a target word, and a dictionary of allowed words, transform the start into the target by changing one letter at a time. Every intermediate word, and the target itself, must appear in the dictionary, and all words share the same length. Return the number of words in the shortest chain including both ends, or 0 when no chain exists.

Examples

Input:  start = hit, target = cog, words = [hot, dot, dog, lot, log, cog]
Output: 5
Why:    hit, hot, dot, dog, cog is five words long
Input:  start = hit, target = cog, words = [hot, dot, dog]
Output: 0
Why:    the target is missing from the dictionary, so nothing can reach it
Input:  start = a, target = c, words = [a, b, c]
Output: 2
Why:    edge case, single letters let the start reach the target directly

Hints

0 / 3

Stuck on the idea rather than the code? Shortest Path, Unweighted covers it.