Graph Theory37 sections · 1633 units
Open in Course

LeetCode 127 Word Ladder - Finding Neighbors

The hard part

Comparing every pair of words takes O(N2×L)O(N^2 \times L) time, where NN is the number of words and LL is word length. That is too slow for large inputs.

Instead, for each word, try changing each letter to every letter in the alphabet. For a word like hot, generate *ot, h*t, ho* by masking each position.

Check if these patterns match any word in the word list. Use a hash map from pattern to words. For hot, check if aot, bot,., zot exist, then hat, hbt,., hzt, and so on. This takes O(L×26)O(L \times 26) per word, much faster than O(N×L)O(N \times L).

Space complexity is O(V)O(V) for the data structures used.