Given two strings ransomNote and magazine, return true if ransomNote can be constructed using the letters from magazine (each letter can be used only once).
ransomNote = "aa", magazine = "aab"trueWe only need letter frequencies — not order. Magazine provides a "budget" of each letter. Each letter used in the ransom note consumes one unit from that budget. If any budget goes negative, we can't build the note.
Searching the magazine for each note letter, and removing it, is O(n·m). Counting letters is much faster.
Count how many of each letter the magazine has. Then go through the note, using up one count per letter. If any count would go below 0, the note is impossible.
"can I build this" problems are letter counts. Add from the supply, subtract for the demand, and watch for negatives.
Run the animation above on your own input, or watch the 1:10 video explanation of Ransom Note with a dry run and Java code.