Skip to content
BASA DSA

Word Ladder

HardGraphs

Transform beginWord into endWord by changing one letter per step. Every word after the start must be in wordList. Return the smallest number of words in such a sequence, or zero if impossible.

Example 1

One-letter transformations among the start and dictionary words. Start: cat; target: dog.One-letter transformations among the start and dictionary words. Start: cat; target: dog. Vertices: node 0: cat, node 1: cot, node 2: cog, node 3: dog, node 4: dat, node 5: dot. Edges: node 0 (cat) — node 1 (cot); node 0 (cat) — node 4 (dat); node 1 (cot) — node 2 (cog); node 1 (cot) — node 5 (dot); node 2 (cog) — node 3 (dog); node 3 (dog) — node 5 (dot); node 4 (dat) — node 5 (dot).catcotcogdogdatdot
One-letter transformations among the start and dictionary words. Start: cat; target: dog.

Input
beginWord = "cat"
endWord = "dog"
wordList = ["cot","cog","dog","dat","dot"]
Output
4

Explanation

cat->cot->cog->dog changes one letter per step and uses four words.

Example 2

One-letter transformations among the start and dictionary words. Start: cat; target: dog (absent from dictionary).One-letter transformations among the start and dictionary words. Start: cat; target: dog (absent from dictionary). Vertices: node 0: cat, node 1: cot, node 2: cog. Edges: node 0 (cat) — node 1 (cot); node 1 (cot) — node 2 (cog).catcotcog
One-letter transformations among the start and dictionary words. Start: cat; target: dog (absent from dictionary).

Input
beginWord = "cat"
endWord = "dog"
wordList = ["cot","cog"]
Output
0

Explanation

dog is absent from the dictionary, preventing a valid final word.

Example 3

One-letter transformations among the start and dictionary words. Start: a; target: c.One-letter transformations among the start and dictionary words. Start: a; target: c. Vertices: node 0: a, node 1: b, node 2: c. Edges: node 0 (a) — node 1 (b); node 0 (a) — node 2 (c); node 1 (b) — node 2 (c).abc
One-letter transformations among the start and dictionary words. Start: a; target: c.

Input
beginWord = "a"
endWord = "c"
wordList = ["a","b","c"]
Output
2

Explanation

a changes directly to c, using two words.

Constraints

  • Words are lowercase and have equal length 1..10
  • beginWord differs from endWord
  • At most 5000 distinct dictionary words

Function contractladderLengthArguments: json, json, json
Loading draft…
SolutionRuns on your device
Loading draft…