Ransom Note

Easy Arrays & Hashing Hashing

Ransom Note is a easy arrays & hashing problem solved with the hashing pattern. The best approach, optimal (count the 26 letters), runs in O(n + m) time and O(1) space. Below are 3 approaches in Java, Python, C++ and JavaScript, from brute force (cross off one letter at a time) up.

Problem

You are given two strings, ransomNote and magazine. You want to write the note by cutting single letters out of the magazine and gluing them together.

Each letter of magazine can be used at most once, and you may use the letters in any order. Letters of the magazine that the note does not need are simply left over.

Return true if ransomNote can be built this way, and false otherwise.

Examples

Example 1

Input
ransomNote = "cab", magazine = "abcd"
Output
true
Why
The magazine has one a, one b and one c, which is all the note needs. The d is simply not used.

Example 2

Input
ransomNote = "noon", magazine = "nobody"
Output
false
Why
The note needs two n's and two o's. The magazine has its two o's, but only one n.

Example 3

Input
ransomNote = "aa", magazine = "ab"
Output
false
Why
The note needs two a's, but the magazine has only one.

Constraints

  • 1 <= ransomNote.length, magazine.length <= 10^5
  • ransomNote and magazine contain only lowercase English letters.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 30 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Animated walkthrough

A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (cross off one letter at a time)O(n * m)O(m)
Sort both and walk togetherO(n log n + m log m)O(n + m)
Optimal (count the 26 letters)O(n + m)O(1)

1Brute force (cross off one letter at a time)

TimeO(n * m)Each of the n letters of the note may scan all m letters of the magazine.
SpaceO(m)The used array has one entry per magazine letter.

Treat the magazine like a sheet you cut letters from. For each letter of the note, search the magazine for a copy that has not been cut out yet. If you find one, mark it as used; if every copy is already used (or there never was one), the note cannot be built. If every letter of the note finds its own copy, it can.

  1. Make a boolean array used, one entry per magazine position, all false.
  2. For each letter c of ransomNote: scan the magazine for a position j with magazine[j] == c and used[j] false.
  3. If there is one, set used[j] = true and go on to the next letter. If not, return false.
  4. Return true when every letter has been matched.
class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        boolean[] used = new boolean[magazine.length()];
        for (int i = 0; i < ransomNote.length(); i++) {
            char c = ransomNote.charAt(i);
            boolean found = false;
            for (int j = 0; j < magazine.length(); j++) {
                if (!used[j] && magazine.charAt(j) == c) {
                    used[j] = true;
                    found = true;
                    break;
                }
            }
            if (!found) return false;
        }
        return true;
    }
}

2Sort both and walk together

TimeO(n log n + m log m)Sorting dominates; the walk itself moves each pointer at most once across its array.
SpaceO(n + m)The sorted character arrays of both strings.

Sort the letters of both strings. Equal letters now sit in one block, and the blocks appear in the same alphabetical order in both. Walk the sorted note with one pointer and the sorted magazine with another. For each note letter, skip past the magazine letters that are smaller (the note never needs them). If the magazine runs out, or the next magazine letter is bigger, the letter we need is not available any more and the answer is false. Otherwise the two letters are equal: use that copy and move both pointers on.

  1. If ransomNote is longer than magazine, return false.
  2. Sort the characters of both strings into arrays a (note) and b (magazine). Set j = 0.
  3. For each letter c in a: while j < b.length and b[j] < c, move j forward.
  4. If j == b.length or b[j] != c, return false. Otherwise move j forward (that copy is used).
  5. Return true.
class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        if (ransomNote.length() > magazine.length()) return false;
        char[] a = ransomNote.toCharArray();
        char[] b = magazine.toCharArray();
        Arrays.sort(a);
        Arrays.sort(b);
        int j = 0;
        for (char c : a) {
            while (j < b.length && b[j] < c) j++;
            if (j == b.length || b[j] != c) return false;
            j++;
        }
        return true;
    }
}

3Optimal (count the 26 letters)

TimeO(n + m)One pass over the magazine and one over the note, with O(1) work per letter.
SpaceO(1)Exactly 26 counters, whatever the input size.

Only the number of copies of each letter matters. Count the magazine's letters in an array of 26 counters, one per letter. Then go through the note and spend one copy for each letter it uses. If a counter would drop below zero, the note asks for more copies of that letter than the magazine has, so return false. If the whole note is spent without that happening, return true. A note longer than the magazine can be rejected at once.

  1. If ransomNote is longer than magazine, return false.
  2. Make count[26] = 0 and add one to count[c - 'a'] for every letter c of magazine.
  3. For every letter c of ransomNote: subtract one from count[c - 'a']; if it becomes negative, return false.
  4. Return true.
class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        if (ransomNote.length() > magazine.length()) return false;
        int[] count = new int[26];
        for (int i = 0; i < magazine.length(); i++) {
            count[magazine.charAt(i) - 'a']++;
        }
        for (int i = 0; i < ransomNote.length(); i++) {
            int c = ransomNote.charAt(i) - 'a';
            count[c]--;
            if (count[c] < 0) return false;
        }
        return true;
    }
}

Edge cases to test

  • The note is longer than the magazine: it can never be built
  • The magazine has the right letters but too few copies of one of them, like "aab" from "abb"
  • Both strings are equal: every letter is used exactly once
  • Single-character strings, equal or different
  • The magazine has many letters the note never needs: extra letters are fine

Hints

Hint 1

Each letter of the magazine can be cut out and used at most once, so only how many times each letter appears matters, not where.

Hint 2

The note can be built exactly when, for every letter, the note needs no more copies than the magazine has.

Hint 3

There are only 26 lowercase letters. Count the magazine's letters in an array of 26, then spend them on the note.

FAQ

What is the best time complexity for Ransom Note?

Optimal (count the 26 letters) runs in O(n + m) time and O(1) extra space. One pass over the magazine and one over the note, with O(1) work per letter.

Which pattern does Ransom Note use?

It is a arrays & hashing problem that uses the hashing pattern. Other problems with the same pattern: Group Anagrams, First Unique Character in a String, Number of Matching Subsequences.

Is there a brute force solution for Ransom Note?

Yes. Brute force (cross off one letter at a time) takes O(n * m) time and O(m) space. Treat the magazine like a sheet you cut letters from.

Which edge cases should I test for Ransom Note?

The note is longer than the magazine: it can never be built; The magazine has the right letters but too few copies of one of them, like "aab" from "abb"; Both strings are equal: every letter is used exactly once; Single-character strings, equal or different; The magazine has many letters the note never needs: extra letters are fine.