Word Ladder - Complete Solution Guide
Word Ladder is LeetCode problem 127, a Hard level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
A transformation sequence from word beginWord to word endWord using a dictionary wordList is a sequence of words beginWord -> s 1 -> s 2 -> ... -> s k such that: Every adjacent pair of words differs by a single letter. Every s i for 1 <= i <= k is in wordList . Note that beginWord does not need to be in wordList . s k == endWord Given two words, beginWord and endWord , and a dictionary wordList , return the number of words in the shortest transformation sequence from beginWord to endWord , or 0
Detailed Explanation
The "Word Ladder" problem asks you to find the shortest transformation sequence from a starting word (`beginWord`) to an ending word (`endWord`), given a dictionary of valid words (`wordList`). Each transformation in the sequence must change only one letter at a time, and every intermediate word must be present in the `wordList`. The goal is to return the length of the shortest such sequence (including the start and end words), or 0 if no such sequence exists. `beginWord` does not have to be present in `wordList`. The length of all words are the same. All words are unique. All inputs are lower case letters.
Solution Approach
The provided code implements a bidirectional Breadth-First Search (BFS) to find the shortest transformation sequence. It starts searching from both the `beginWord` and `endWord` simultaneously. In each iteration, it expands the search from the queue with fewer elements to improve performance. It keeps track of visited words for both searches using separate hash maps (or hash tables). When a word is encountered that has already been visited by the other search, it means a path has been found connecting the `beginWord` and `endWord`, and the algorithm returns the combined length of the paths.
Step-by-Step Algorithm
- Step 1: Check if the `endWord` is present in the `wordList`. If not, return 0 because no transformation sequence is possible.
- Step 2: Initialize two queues (`q_begin` and `q_end`) for BFS, starting with `beginWord` and `endWord` respectively.
- Step 3: Initialize two hash maps (`visited_begin` and `visited_end`) to keep track of visited words and their levels (distance from the starting word) for each search direction.
- Step 4: While both queues are not empty:
- Step 5: Select the queue with the smaller size. Swap the `q_begin`, `q_end`, `visited_begin`, and `visited_end` if `q_begin` is larger than `q_end`.
- Step 6: Dequeue a word (`word`) from the selected queue (`q_begin`). Get its level (`level`) from the corresponding `visited_begin` hash map.
- Step 7: Iterate through each character of the current `word`:
- Step 8: For each character, try replacing it with all possible lowercase letters ('a' to 'z'):
- Step 9: Create a new word (`next_word`) with the replaced character.
- Step 10: Check if `next_word` is in the `visited_end` hash map. If yes, it means a path connecting `beginWord` and `endWord` has been found. Return the sum of the levels from both sides (i.e., `level + visited_end[next_word]`).
- Step 11: If `next_word` is in the `wordList` and not in the `visited_begin` hash map, it's a valid and unvisited word. Enqueue it into `q_begin`, update its level in `visited_begin` to `level + 1`.
- Step 12: If no path is found after exhausting both queues, return 0.
Key Insights
- Insight 1: The problem can be modeled as a graph where each word is a node, and an edge exists between two words if they differ by only one letter. The shortest transformation sequence is then equivalent to the shortest path in this graph.
- Insight 2: Breadth-First Search (BFS) is the ideal algorithm for finding the shortest path in an unweighted graph.
- Insight 3: A bidirectional BFS can significantly improve performance by searching from both the `beginWord` and the `endWord` simultaneously. The search stops when the two searches meet at a common word.
Complexity Analysis
Time Complexity: O(M^2 * N)
Space Complexity: O(M * N)
Topics
This problem involves: Hash Table, String, Breadth-First Search.
Companies
Asked at: Box, Juspay, LinkedIn, Navan, Nutanix, PhonePe, Reddit, Samsung, Snap, Tekion, The Trade Desk, TikTok, Uber, Visa, Yahoo, Yelp, ZScaler, eBay.