Ransom note

Can the ransom note be built using only the letters available in the magazine? Count, then spend.

Time O(m + n)Space O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Count every letter available in the magazine once. Then walk the ransom note and spend one copy of each letter it needs. If a letter is ever missing, or every copy has already been spent, the note cannot be built.

Code

public static bool CanConstruct(string note, string magazine) {
    var letters = new Dictionary<char, int>();
    foreach (char c in magazine) letters[c] = letters.GetValueOrDefault(c) + 1;
    foreach (char c in note) {
        if (!letters.TryGetValue(c, out int n) || n == 0) return false;
        letters[c] = n - 1;
    }
    return true;
}
static boolean canConstruct(String note, String magazine) {
    Map<Character, Integer> letters = new HashMap<>();
    for (char c : magazine.toCharArray()) letters.merge(c, 1, Integer::sum);
    for (char c : note.toCharArray()) {
        int n = letters.getOrDefault(c, 0);
        if (n == 0) return false;
        letters.put(c, n - 1);
    }
    return true;
}
bool canConstruct(const string& note, const string& magazine) {
    unordered_map<char, int> letters;
    for (char c : magazine) letters[c]++;
    for (char c : note) {
        if (letters[c] == 0) return false;
        letters[c]--;
    }
    return true;
}
def can_construct(note: str, magazine: str) -> bool:
    letters = {}
    for c in magazine: letters[c] = letters.get(c, 0) + 1
    for c in note:
        if letters.get(c, 0) == 0: return False
        letters[c] -= 1
    return True

Tips

In the .NET library

Because only subtraction happens while reading the note, never addition, a letter count can only reach zero and then fail - the explicit n == 0 check is what catches a letter that has already been fully spent.