KatInterview

Minimum Steps in Word Ladder

Trees & GraphsAuto-graded · 23 test cases
MediumAuto-gradedTrees & Graphsbfsgraphstring

Last updated

Tests BFS on an implicit graph with efficient neighbor generation using wildcard pattern indexing.

You are given two words source and target of equal length, along with a list of valid words. In a single step, you may change exactly one letter in your current word to produce a new word that must appear in the valid word list.

Determine the minimum number of steps required to transform source into target. If no such transformation exists, return -1.

Rules:

  • Only words of the same length as source and target are considered valid.
  • The target word must be present in the valid word list.
  • The source word does not need to be in the list initially.
  • If source and target are identical, return 0 regardless of whether they appear in the word list.
  • If source and target have different lengths, return -1.

Constraints:

  • 1 <= len(source) <= 10
  • 1 <= len(target) <= 10
  • 0 <= len(words) <= 5000
  • All words consist of lowercase English letters
  • source != "" and target != ""

Examples

Example 1

Input: min_word_ladder_steps('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log', 'cog'])

Output: 4

Example 2

Input: min_word_ladder_steps('hit', 'cog', ['hot', 'dot', 'dog', 'lot', 'log'])

Output: -1

Example 3

Input: min_word_ladder_steps('same', 'same', [])

Output: 0

Hints

Hint 1

Model this as a shortest path problem where each word is a node and edges connect words differing by one letter.

Hint 2

Use BFS to explore words level by level, guaranteeing the first path found to the target is shortest.

Hint 3

Generate neighbors efficiently by creating wildcard patterns (e.g., 'h*t' matches 'hot', 'hit') and grouping words by shared patterns.