Word Ladder: the idea to remember.
Return the number of words in the shortest single letter transformation from beginWord to endWord through a dictionary.
The core insight
Explore words by increasing transformation distance, using wildcard patterns to find one letter neighbors.
Why it works
Each transformation has equal cost, so the first breadth first arrival at the target has minimum length.
The mistake to avoid
The answer counts words, not edges. The end word must belong to the dictionary.
Commented Java solution
Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.
int ladderLength(String beginWord, String endWord, List<String> wordList) {
Set<String> words = new HashSet<>(wordList);
if (!words.contains(endWord)) return 0;
words.add(beginWord);
Map<String,List<String>> patterns = new HashMap<>();
for (String word : words) for (int i = 0; i < word.length(); i++) {
String key = word.substring(0,i) + "*" + word.substring(i+1);
patterns.computeIfAbsent(key, ignored -> new ArrayList<>()).add(word);
}
Queue<String> queue = new ArrayDeque<>();
Set<String> seen = new HashSet<>();
queue.add(beginWord); seen.add(beginWord);
int length = 1;
while (!queue.isEmpty()) {
for (int count = queue.size(); count > 0; count--) {
String word = queue.remove();
if (word.equals(endWord)) return length;
for (int i = 0; i < word.length(); i++) {
String key = word.substring(0,i) + "*" + word.substring(i+1);
// A wildcard bucket only needs to be expanded once.
List<String> neighbors = patterns.remove(key);
if (neighbors != null) for (String next : neighbors)
if (seen.add(next)) queue.add(next);
}
}
length++;
}
return 0;
}
Make the next connection
Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.