Ransom Note

Try to solve the Ransom Note problem.

Statement#

Given two strings, ransom_note and magazine, check if ransom_note 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 ransom_note.length , magazine.length 105\leq 10^5

  • The ransom_note and magazine consist of lowercase English letters.

Examples#

Created with Fabric.js 3.6.6 Output Ransom note "baad" Magazine "abcd" FALSE Input Sample example 1

1 of 4

Created with Fabric.js 3.6.6 Output Input Ransom note "bad" Magazine "abcd" TRUE Sample example 2

2 of 4

Created with Fabric.js 3.6.6 Output FALSE Input Ransom note "code" Magazine "abcodf" Sample example 3

3 of 4

Created with Fabric.js 3.6.6 Input TRUE Ransom note "program" Magazine "rpgoarm" Output Sample example 4

4 of 4

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 = “problemsolving”

magazine = “adsoptendroblemfemopvinxtbml”

A)

Yes

B)

No

Question 1 of 40 attempted

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.

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

Iterate through each character in the ransom note.

Return TRUE if all characters in the ransom note have been successfully traversed.

If the frequency of the character is 0 or it is not available in the hash map, return FALSE.

Create a hash map to store the frequencies of each character in the magazine.

Check if the character is present in the hash map and its count is greater than 0. If yes, decrement the frequency of the character in the hash map by 1.


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.

Python
usercode > main.py
Input #1
Input #2
Ransom Note

Solution: Majority Element

Solution: Ransom Note