FunctionRacerProblemsRace

One Letter at a Time

HardGraphsPython, JavaScript, TypeScript, Java, C++

You want to turn the word start into the word goal. One step changes a single letter, and the word you get must be on the list words. The word start itself does not have to be on the list.

Return the fewest steps, or -1 if goal cannot be reached. If start equals goal, the answer is 0.

Example 1

start "cold"
goal "warm"
words ["cord","card","ward","warm","word","worm"]
returns 4

cold, cord, card, ward, warm: four steps. The way over word and worm is just as long.

Example 2

start "aa"
goal "bb"
words ["bb"]
returns -1

Both letters differ, and the only word on the list is the goal itself: no single change leads anywhere.

Example 3

start "aa"
goal "aa"
words ["zz"]
returns 0

Nothing has to change.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Graphs problems