Intuitive Javascript Solution


  • 0
    D
    var intersect = function(nums1, nums2) {
        const toSet = (set, n) => {
            set[n] ? set[n] += 1 : set[n] = 1;
            return set;
        };
        const set1 = nums1.reduce(toSet, {});
        const set2 = nums2.reduce(toSet, {});
        
        // find common numbers and their minimum occurrences as intersections
        return Object.keys(set1).reduce((intersection, key) => {
            if (set2[key])
                for (let i = 0; i < Math.min(set1[key], set2[key]); i++) 
                    intersection.push(+key);
    
            return intersection;
        }, []);
    };
    

Log in to reply
 

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