Problem solution · Python

Word Ladder II

Word Ladder II: a Python solution using hash-based lookup. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Hash-based lookup
Source
walkccc LeetCode Solutions
Length
77 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Hash-based lookup

For Word Ladder II, the implementation stores previously seen values or frequencies in a hash table for direct membership and lookup operations.

  1. Decide the key that represents the information needed later.
  2. Update its count or stored state while scanning the input.
  3. Use constant-time expected lookups to detect matches or assemble the result.

Code notes

  • 77 lines of Python from the credited upstream file 126.py.
  • The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
  • No explicit loop blocks detected.

Complexity

Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeWord Ladder II · PythonPython
Use this to learn the idea, then write your own version.
class Solution:  def findLadders(self, beginWord: str, endWord: str, wordList: list[str]) -> list[list[str]]:    wordSet = set(wordList)    if endWord not in wordList:      return []     # {"hit": ["hot"], "hot": ["dot", "lot"], ...}    graph: dict[str, list[str]] = collections.defaultdict(list)     # Build the graph from the beginWord to the endWord.    if not self._bfs(beginWord, endWord, wordSet, graph):      return []     ans = []    self._dfs(graph, beginWord, endWord, [beginWord], ans)    return ans   def _bfs(      self,      beginWord: str,      endWord: str,      wordSet: set[str],      graph: dict[str, list[str]],  ) -> bool:    currentLevelWords = {beginWord}     while currentLevelWords:      for word in currentLevelWords:        wordSet.discard(word)      nextLevelWords = set()      reachEndWord = False      for parent in currentLevelWords:        for child in self._getChildren(parent, wordSet):          if child in wordSet:            nextLevelWords.add(child)            graph[parent].append(child)          if child == endWord:            reachEndWord = True      if reachEndWord:        return True      currentLevelWords = nextLevelWords     return False   def _getChildren(self, parent: str, wordSet: set[str]) -> list[str]:    children = []    s = list(parent)     for i, cache in enumerate(s):      for c in string.ascii_lowercase:        if c == cache:          continue        s[i] = c        child = ''.join(s)        if child in wordSet:          children.append(child)      s[i] = cache     return children   def _dfs(      self,      graph: dict[str, list[str]],      word: str,      endWord: str,      path: list[str],      ans: list[list[str]],  ) -> None:    if word == endWord:      ans.append(path.copy())      return     for child in graph.get(word, []):      path.append(child)      self._dfs(graph, child, endWord, path, ans)      path.pop() 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗