/127. Word Ladder

127. Word Ladder

Hard
Hash Table45% acceptance

Given two strings start_word and target_word, and a list of strings dictionary_words, return the minimum number of words in a sequence starting with start_word and ending with target_word, where each consecutive pair of words differs by exactly one character and each intermediate word is in dictionary_words. If no such sequence exists, return 0. The sequence must include target_word and may include start_word even if it is not in dictionary_words.

Example 1

Input: start_word = lead, target_word = gold, dictionary_words = [load, goad, gold, gald]

Output: 4

Explanation: lead -> load -> goad -> gold

Example 2

Input: start_word = game, target_word = math, dictionary_words = [came, mate, math, gath]

Output: 4

Explanation: game -> came -> mate -> math

Example 3

Input: start_word = cold, target_word = warm, dictionary_words = [cord, card, ward, warm]

Output: 5

Explanation: cold -> cord -> card -> ward -> warm

Example 4

Input: start_word = spin, target_word = spot, dictionary_words = [spit, spot, span, span]

Output: 3

Explanation: spin -> spit -> spot

Example 5

Input: start_word = rock, target_word = roll, dictionary_words = [roil, roll, rokl, rocl]

Output: 3

Explanation: rock -> roil -> roll

Constraints

  • 1 <= len(start_word) <= 10
  • len(target_word) == len(start_word)
  • 1 <= len(dictionary_words) <= 5000
  • All words in dictionary_words have length equal to start_word
  • start_word, target_word, and all dictionary_words consist of lowercase English letters
  • start_word != target_word
  • All words in dictionary_words are unique
Python (current runtime)

Case 1

Input: start_word = 'tone', target_word = 'gone', dictionary_words = ['gone', 'cone', 'hone', 'zone']

Expected: 3

Case 2

Input: start_word = 'lamp', target_word = 'limp', dictionary_words = ['limp', 'lump', 'lamp']

Expected: 2

Case 3

Input: start_word = 'fast', target_word = 'slow', dictionary_words = ['fist', 'slot', 'slat', 'slow']

Expected: 0

Case 4

Input: start_word = 'pool', target_word = 'poll', dictionary_words = ['poll', 'pall', 'pole', 'pool']

Expected: 2

Case 5

Input: start_word = 'fire', target_word = 'hire', dictionary_words = ['hire', 'fite', 'fice', 'fire']

Expected: 2