HardHash TableStringBreadth-First Search

Word Ladder

LeetCode
1 approach, code in all languages

You are given two words, beginWord and endWord, together with a dictionary wordList.

A transformation sequence starts at beginWord and ends at endWord. At each step you may change exactly one letter, and every word produced after the first step must appear in wordList. Note that beginWord itself does not need to be in wordList.

Return the number of words in the shortest transformation sequence from beginWord to endWord. If no such sequence exists, return 0.

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", which contains 5 words.

Example 2

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

Output: 0

endWord "cog" is not present in wordList, so no valid sequence can end at it.

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now