Simple JavaScript O(m + n) solution using map


  • 0
    var findRestaurant = function(list1, list2) {
        const indexes = {};
        for (let i = 0; i < list1.length; i++) {
            indexes[list1[i]] = i;
        }
        let min = Infinity;
        for (let i = 0; i < list2.length; i++) {
            if (list2[i] in indexes) {
                min = Math.min(min, indexes[list2[i]] + i);
            }
        }
        return list2.filter((place, i) => indexes[place] + i === min);
    };
    

Log in to reply
 

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