Problem · Graph

Determine the Edit Distance in a Word Ladder

Learn this problem
MediumAdobeOA

Problem statement

Given two words (beginWord and endWord), and a dictionary's word list, find the minimum number of operations needed to change beginWord into endWord.

You can change only one letter at a time, and each intermediate word must exist in the word list. If there is no possible transformation, return None (Python), -1 (Java & C++), null (Javascript).

Function

ladderLength(beginWord: String, endWord: String, wordList: List<String>) → int

Examples

Example 1

beginWord = "hit"endWord = "cog"wordList = ["hit", "hot", "dot", "dog", "cog"]return = 4

The transformation sequence can be: hit -> hot -> dot -> dog -> cog, which is 4 steps long.

Example 2

beginWord = "word"endWord = "word"wordList = ["word", "ward"]return = 0

Since the beginWord is the same as the endWord, no transformation is needed, so the number of steps is 0.

Example 3

beginWord = "hit"endWord = "cog"wordList = ["hit", "hot", "dot", "dog"]return = -1

The word cog is not in the list, so there is no possible transformation sequence.

More Adobe problems

drafts saved locally
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
  // write your code here
}
beginWord"hit"
endWord"cog"
wordList["hit", "hot", "dot", "dog", "cog"]
expected4
checking account