Not sure what is wrong with my code, Run code seems fine but Submit is throwing up TimeOut exception. Please Help!


  • 0
    V
    public class Solution {
        
        public int ladderLength(String beginWord, String endWord, List<String> wordList) {
            if (wordList == null || wordList.size() == 0 || !wordList.contains(endWord)) {
                return 0;
            }
            wordList.remove(beginWord);
            
            Set<String> leftSet = new HashSet<>();
            Set<String> rightSet = new HashSet<>();
            
            leftSet.add(beginWord);
            rightSet.add(endWord);
            int distance = 1;
            Set<String> visited = new HashSet<>();
            int len = beginWord.length();
            while (!leftSet.isEmpty() && !rightSet.isEmpty()) {
                if (leftSet.size() > rightSet.size()) {
                    Set<String> leftout = rightSet;
                    rightSet = leftSet;
                    leftSet = leftout;
                }
                
                Set<String> temp = new HashSet<>();
                for (String word : leftSet) {
                    char[] chs = word.toCharArray();
                    for (int i = 0; i < len; i++) {
                        for (char ch = 'a'; ch <= 'z'; ch++) {
                            char old = chs[i];
                            chs[i] = ch;
                            String newWord = String.valueOf(chs);
                            if (rightSet.contains(newWord)) {
                                return distance + 1;
                            }
                            
                            if ( !visited.contains(newWord) && wordList.contains(newWord)) {
                                temp.add(newWord);
                                visited.add(newWord);
                            }
                            chs[i] = old;
                        }
                    }
                }
                
                leftSet = temp;
                distance++;
            }
    
            return 0;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.