For Administrators


  • 0
    N

    @administrators

    I coded the Word Ladder in JS, but it keeps getting an TLE error. Passed 30/39 cases. I compared my code with lots of solution posts in other languages, I think the algorithm is the same. Basically, it's just using a two directional BFS on a graph. Can you please take a look at my code? If JS is slower by default compared with other languages, are they having the same time limit? Also, there're so few discussions/solution posts in JS in general, hope this could get improved. Since JS is becoming a more and more important language, I hope your site could provide more solutions/guidance/help to JS coders.

    '''

    var ladderLength = function(beginWord, endWord, wordList) {

    if (wordList.indexOf(endWord) < 0) return 0;
    var beginSet = [];
    var endSet = [];
    beginSet[0] = beginWord;
    endSet[0] = endWord;
    var step = 2;
    
    wordList.splice(wordList.indexOf(beginWord), 1);
    wordList.splice(wordList.indexOf(endWord), 1);
    
    
    while (beginSet.length != 0) {
        if (beginSet.length > endSet.length) {
            var temp = beginSet;
            beginSet = endSet;
            endSet = temp;
        }
        var next = [];
        
        for (var i = 0; i < beginSet.length; i++) {
            // the adjacent neighbors of each node in the graph is the length of the word * 26 (chars)
            var word = beginSet[i];
            for (var j = 0; j < word.length; j++) {
                for (var k = 97; k < 123; k++) {
                    var newWord = word;
                    // newWord = word.substr(0, j) + String.fromCharCode(k) + word.substr(j + 1, word.length - j - 1); // 97 is 'a'
                    newWord = newWord.split('');
                    newWord[j] = String.fromCharCode(k);
                    newWord = newWord.join('');
                    
                    if (endSet.indexOf(newWord) > -1 ) 
                        return step;
                    if (wordList.indexOf(newWord) > -1) {
                        next.push(newWord);
                        wordList.splice(wordList.indexOf(newWord), 1);
                    }
                }
            }
        }
        if (next > endSet) {
            beginSet = endSet;
            endSet = next;
        }
        else {
            beginSet = next;
        }
        step++;
    }
    
    return 0;
    

    };
    '''


Log in to reply
 

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