Skip to main content

Command Palette

Search for a command to run...

word ladder

Published
1 min readView as Markdown
class Solution {

    public int ladderLength(String beginWord, String endWord, List<String> wordList) {
        Queue<String> queue = new LinkedList<>();
        queue.add(beginWord);

        boolean[] visited = new boolean[wordList.size()];
        int level = 0;

        while (!queue.isEmpty()) {
            int currentLevelSize = queue.size();

            while (currentLevelSize > 0) {
                currentLevelSize--;

                String currentWord = queue.remove();

                if (currentWord.equals(endWord)) {
                    return level + 1;
                }

                for (int i = 0; i < wordList.size(); i++) {
                    if (!visited[i]) {
                        String candidateWord = wordList.get(i);

                        if (isOneLetterDiff(currentWord, candidateWord)) {
                            visited[i] = true;
                            queue.add(candidateWord);
                        }
                    }
                }
            }

            level++;
        }

        return 0;
    }

    public static boolean isOneLetterDiff(String word1, String word2) {
        int diffCount = 0;
        int index = 0;

        while (index < word1.length()) {
            char c1 = word1.charAt(index);
            char c2 = word2.charAt(index);

            if (c1 != c2) {
                diffCount++;
            }

            index++;
        }

        return diffCount == 1;
    }
}

More from this blog

Amit singh's blog

235 posts