JavaScript 122ms recursive Solution


  • 1
    B

    I have a JS solution that runs at 122ms (beating 100% of JS solutions yet). Any improvements or suggestions, please feel free to comment.

    /**
     * @param {string[][]} tickets
     * @return {string[]}
     */
    var findItinerary = function(tickets) {
        
        var length = tickets.length;
        
        var map = {
            JFK: []
        };
        
        var result = [];
        
        for(var i=0; i<length; i++){
            
            var from = tickets[i][0];
            var to = tickets[i][1];
            
            if(!map[from]){
                map[from] = [];
                map[from].push(to);
            } else {
                map[from].push(to);
            }
        }
        
        for(var prop in map){
            map[prop].sort();
        }    
        
        makeItinerary("JFK");    // dfs
        
        function makeItinerary(from){        
            var tos = map[from];        
            while(tos && tos.length > 0){
                makeItinerary(tos.shift()); 
            }        
            result.unshift(from);
        }
        
        return result;    
    };
    
    

Log in to reply
 

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