Intuitive Javascript Solution


  • 0
    D
    var canConstruct = function(ransomNote, magazine) {
        // collect maps of number of character occurance 
        let ransomNoteMap = ransomNote.split('').reduce((map, crr) => {
            if (!map[crr]) map[crr] = 0;
            map[crr]++;
            return map;
        }, {});
        let magazineMap = magazine.split('').reduce((map, crr) => {
            if (!map[crr]) map[crr] = 0;
            map[crr]++;
            return map;
        }, {});
        let ransomeNoteKeys = Object.keys(ransomNoteMap);
        
        // false if no or not enough characters in magazine
        for(const key of ransomeNoteKeys)
            if (!magazineMap[key] || magazineMap[key] < ransomNoteMap[key]) return false;
        
        return true;
    };
    
    

Log in to reply
 

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