26 · Graphs: BFS & DFS

#127 Word Ladder

Hardsolve on LeetCode ↗

frequently reported atLinkedInAmazonByteDance / TikTokAppleMetaMicrosoft

the problem

In plain words

Transform beginWord into endWord by changing one letter at a time; every intermediate word must be in wordList. Return the number of words in the shortest sequence (including both ends), or 0 if impossible.

in beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]

out 5

hit → hot → dot → dog → cog.

in beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]

out 0

"cog" is not in the list.

  • 1 ≤ word length ≤ 10
  • 1 ≤ wordList.length ≤ 5000
  • Lowercase letters; all words the same length and unique; beginWord ≠ endWord

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #433
    2. #909
      Snakes and Ladders
      Mediumin Graphs
    3. #1091