Skip to main content
Back to problems
Leetcode
Hard
Graphs
Strings
Hash Maps
Queues
Google
Meta
Amazon
Word Ladder

Find the shortest sequence of one-letter transformations from a start word to a target word, where every intermediate word must be valid.

Acceptance 0%
Problem Statement

Given a beginWord, an endWord, and a list of allowed words, transform beginWord into endWord by changing exactly one character at a time.

Every intermediate word must exist in the given list of allowed words. Return the number of words in the shortest valid transformation sequence, including both the start and end words. If no such sequence exists, return 0.

This is an unweighted shortest-path problem over an implicit graph whose vertices are words and whose edges connect words that differ by one character.

Input Format

  • beginWord: starting string
  • endWord: target string
  • wordList: array of allowed strings

All words are assumed to have the same length.

Output Format

Return an integer: the length of the shortest valid transformation sequence, or 0 if the target cannot be reached.

Constraints

  • Change only one character per step.
  • Each intermediate word must be in wordList.
  • beginWord is not required to be in wordList.
  • If endWord is not in wordList, the answer is 0.
  • Words are non-empty and have equal length.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

5

Explanation

One shortest sequence is: hit -> hot -> dot -> dog -> cog. The sequence length is 5.

Example 2

Input

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

Output

0

Explanation

The target word "cog" is not reachable because it is not present in the allowed list.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.