Search⌘ K
AI Features

Ransom Note

Understand how to determine if a ransom note can be formed from a magazine's letters by tracking letter frequencies. Learn to apply efficient counting patterns to solve this problem in linear time and constant space, a common challenge in coding interviews.

Statement

Given two strings, ransomNote and magazine, check if ransomNote can be constructed using the letters from magazine. Return TRUE if it can be constructed, FALSE otherwise.

Note: A ransom note is a written message that can be constructed by using the letters available in the given magazine. The magazine can have multiple instances of the same letter. Each instance of the letter in the magazine can only be used once to construct the ransom note.

Constraints:

  • 11 \leq ransomNote.length , magazine.length 103\leq 10^3

  • The ransomNote and magazine consist of lowercase English letters.

Examples

Understanding the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Ransom Note

1.

For the following strings, can we generate the ransom note using the letters from the magazine string?

ransom note = “youhaveakindheart”

magazine = “abecdefghiavjklmaonopqhrtuvweaxyz”

A.

Yes

B.

No


1 / 4

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

We have left the solution to this challenge as an exercise for you. An optimal solution to this problem runs in O(n + m) time and takes O(1) space. You may try to translate the logic of the solved puzzle into a coded solution.

Java
usercode > Solution.java
import java.util.*;
public class Solution {
public static boolean canConstruct(String ransomNote, String magazine) {
// Replace this placeholder return statement with your code
return false;
}
}
Ransom Note