Hash Tables: Ransom Note

  • + 0 comments

    ts

    function checkMagazine(magazine: string[], note: string[]): void {
        if(magazine.length < note.length){
            console.log("No")
            return
        }
            
        const magazineMap = new Map<string, number>()
        magazine.forEach( (magazineWord) => {
            const value = magazineMap.get(magazineWord) ? magazineMap.get(magazineWord) + 1 : 1
            magazineMap.set(magazineWord, value)
        })
        
        for(const word of note){
            if(!magazineMap.has(word)){
                console.log("No")
                return
            }
            const currentValue = magazineMap.get(word)
            if(currentValue - 1 === 0){
                magazineMap.delete(word)
            }else {
                magazineMap.set(word, currentValue -1)
            }
        }
        console.log("Yes")
    }