/126. Word Ladder II

126. Word Ladder II

Hard
Hash Table27.6% acceptance

Given a start string start_word, a target string target_word, and a list of strings dictionary, find all shortest sequences of transformations from start_word to target_word. Each transformation changes exactly one character and the resulting word must be in dictionary. Return all shortest transformation sequences as lists of strings, or an empty list if no sequence exists. Each sequence must begin with start_word and end with target_word.

Example 1

Input: start_word=lead, target_word=gold, dictionary=[load,goad,gold,leap,goap]

Output: [[lead,load,goad,gold]]

Explanation: The shortest transformation is lead -> load -> goad -> gold.

Example 2

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

Output: [[game,came,mate,math]]

Explanation: The shortest transformation is game -> came -> mate -> math.

Example 3

Input: start_word=stone, target_word=money, dictionary=[stony,monny,money,stane,stony]

Output: []

Explanation: No valid transformation sequence exists.

Constraints

  • 1 <= len(start_word) <= 5
  • len(target_word) == len(start_word)
  • 1 <= len(dictionary) <= 500
  • All words in dictionary have length equal to start_word
  • start_word, target_word, and all words in dictionary consist of lowercase English letters
  • start_word != target_word
  • All words in dictionary are unique
  • The total number of shortest transformation sequences does not exceed 10^5
Python (current runtime)

Case 1

Input: start_word='cold', target_word='warm', dictionary=['cord','card','ward','warm','worm','word']

Expected: [['cold','cord','card','ward','warm']]

Case 2

Input: start_word='fast', target_word='slow', dictionary=['last','slat','slot','slow','flaw']

Expected: [['fast','last','slat','slot','slow']]

Case 3

Input: start_word='play', target_word='stay', dictionary=['plax','stax','stay','plat','stat']

Expected: [['play','plat','stat','stax','stay']]

Case 4

Input: start_word='moon', target_word='noon', dictionary=['moan','noon','mood','monn']

Expected: [['moon','monn','noon']]

Case 5

Input: start_word='rock', target_word='sock', dictionary=['sock','sack','rack','roak']

Expected: [['rock','rack','sack','sock']]