Applied AI Engineer (LLM) coding learning path Level 2 This level · 21 of 31

How do you find the length of the shortest word ladder?

Hard BFS Hash map String

Problem

You are given beginWord, endWord and a dictionary wordList. A legal step changes exactly one letter, and every intermediate word must be in the list; beginWord itself does not have to be. Return the number of words in the shortest such sequence, or 0 if none exists.

Original: LeetCode 127: Word Ladder.

Examples

Example 1

Input`beginWord = "hit", endWord = "cog", wordList = ["hot", "dot", "dog", "lot", "log", "cog"]`
Output`5`

One shortest sequence is hit -> hot -> dot -> dog -> cog. It has five words and four transformations.

Example 2

Input`beginWord = "hit", endWord = "cog", wordList = ["hot", "dot", "dog", "lot", "log"]`
Output`0`

cog is not in the list, so no legal sequence exists.

Constraints

  • 1 <= beginWord.length <= 10
  • endWord.length == beginWord.length
  • 1 <= wordList.length <= 5000
  • wordList[i].length == beginWord.length
  • beginWord, endWord, and wordList[i] consist of lowercase English letters.
  • beginWord != endWord
  • All the words in wordList are unique.

Hints

Solution

Tried it yourself? The approach, complexity, and code stay hidden until you choose.

Sources (2)
  1. LeetCode 127: Word Ladderleetcode.com
  2. Sedgewick and Wayne, Algorithms, 4th edition, section 4.1, Breadth-first searchalgs4.cs.princeton.edu
Previous
Next