Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Shortest word transformation

Hard · Target 30 minutes · Graphs · Type asked atAmazonMetaGoogle

Given a beginWord, an endWord and a dictionary wordList of words of the same length, a transformation sequence starts at beginWord, changes exactly one letter at each step, and every word after the first must be in wordList. Return the number of words in the shortest sequence that ends at endWord, counting both ends, or 0 if there is none. beginWord need not be in the list.

Examples

InputOutputWhy
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]5hit → hot → dot → dog → cog.
beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]0"cog" is not in the list, so it cannot be used.
beginWord = "lead", endWord = "gold", wordList = ["load","goad","gold","lean","mead"]4lead → load → goad → gold.

Constraints

  • 1 ≤ word length ≤ 10
  • 1 ≤ wordList.length ≤ 5000
  • Lowercase letters only; the list has no duplicates

Hints

Hint 1

Each word is a node, with an edge between words that differ in one letter. The question asks for a shortest path: breadth-first search.

Hint 2

Comparing every pair of words costs O(n² · L). Generate neighbours instead: change each position to each of the 26 letters and look the result up in a set.

Hint 3

Remove a word from the set when it is queued, so it is never queued twice.

Where people lose marks

  • Returning the number of steps (edges) instead of the number of words: off by one.
  • Allowing the end word when it is not in the list.
  • Building all n² edges up front, which times out at 5,000 words.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.