Skip to content

Instantly share code, notes, and snippets.

@decagondev
Created April 23, 2025 21:16
Show Gist options
  • Save decagondev/4ad055a657d3c726227faa7f46a015a5 to your computer and use it in GitHub Desktop.
Save decagondev/4ad055a657d3c726227faa7f46a015a5 to your computer and use it in GitHub Desktop.

PROBLEM 8: Word Ladder

Problem Statement

Given two words, beginWord and endWord, and a dictionary wordList, return the length of the shortest transformation sequence from beginWord to endWord, such that:

  1. Only one letter can be changed at a time.
  2. Each transformed word must exist in the wordList.

Return 0 if no such sequence.

Concepts Covered

  • BFS for shortest path in implicit graphs
  • Graph modeling of words

Examples

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: "hit" -> "hot" -> "dot" -> "dog" -> "cog"

Input: beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
Output: 0

Starter Code

def ladder_length(beginWord: str, endWord: str, wordList: list[str]) -> int:
    # Implement your solution here
    pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment