127. Word Ladder

Given two words (beginWord_and_endWord), and a dictionary's word list, find the length of shortest transformation sequence frombeginWord_to_endWord, such that:

  1. Only one letter can be changed at a time.

  2. Each transformed word must exist in the word list. Note that beginWord is not a transformed word.

Note:

  • Return 0 if there is no such transformation sequence.

  • All words have the same length.

  • All words contain only lowercase alphabetic characters.

  • You may assume no duplicates in the word list.

  • You may assume beginWord and endWord are non-empty and are not the same.

Example 1:

Input:

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

Output: 5

Explanation: As one shortest transformation is "hit" ->"hot" -> "dot" -> "dog" -> "cog",return its length 5.

Example 2:

Thoughts:

  1. BFS: Generate the qualified permutation, add distance by 1, until find the answer or queue is empty

  2. Optimizations:

    1. Python:

        1. Character flopping: flop (expanding the transformation candidate in the "front" set, then check whether it is in the word dictionary: T: O(M*26*L*L); O(L) . M: Dictionary Size, L: word length,

        1. Dictionary Checking: Checking whether a word in current wordDictionary can be transformed into current word in the set: T:O(MNL). N: number of words in the dictionary.

      1. Removing entries in S from T vs Creating new entries from S if it is not in T.

Code

Code: Python Optimization

Code: C++ OptimizationThe above code can still be speeded up if we also begin fromend. Once we meet the same word fromstartandend, we know we are done.This link provides a nice two-end search solution. I rewrite the code below for better readability. Note that the use of two pointerspheadandptailsave a lot of time. At each round of BFS, depending on the relative size ofheadandtail, we pointpheadto the smaller set to reduce the running time.

Last updated

Was this helpful?