Word Ladder (Shortest Path) in Java: Explanation & Practice

Find shortest transformation sequence

Problem summary

Given beginWord, endWord, and a dictionary, find the length of shortest transformation sequence. Each step changes one letter to form a word in the dictionary.

Starter code

public class Main {
    public static void main(String[] args) {
        String beginWord = "hit";
        String endWord = "cog";
        String[] wordList = {"hot","dot","dog","lot","log","cog"};
        
        // BFS from beginWord
        // Generate all possible one-letter changes
        // Check if in dictionary
        // Print: Length: 5
    }
}

Expected output and test cases

  • hit→hot→dot→dog→cog
    Length: 5
  • endWord not in list
    Length: 0
  • Direct transformation possible
    Length: 2

Hints

  1. BFS gives shortest path in unweighted graph
  2. Each word is a node, edges connect words differing by one letter
  3. Use HashSet for O(1) dictionary lookup
  4. Remove words from set once visited to avoid cycles

Related Data Structures & Algorithms exercises

Practice all Data Structures & Algorithms exercises · Run this idea in the Java compiler