Problem 383: Ransom Note
Question
LeetCode Link | 383. Ransom Note | Easy
Given two strings ransomNote
and magazine
, return true
if ransomNote
can be constructed by using the letters from magazine
and false
otherwise.
Each letter in magazine
can only be used once in ransomNote
.
Constrains
1 <= ransomNote.length, magazine.length <= 10^5
ransomNote
andmagazine
consist of lowercase English letters.
Examples
Example 1
Input: ransomNote = “a”, magazine = “b”
Output: false
Example 2
Input: ransomNote = “aa”, magazine = “ab”
Output: false
Example 3
Input: ransomNote = “aa”, magazine = “aab”
Output: true
Solution Approach
Method: Array / Hash Table
Constrains
- None
This method does not have any limitations.
Concept Explanation
This question is similar with question 242. Valid Anagram. It does not require same same character count in this question but only if the character in rasnsom note is in scope of magazine. Thus, we could use array with hash method, which is similar with question 242.
Why not use map?
In this case, using a map consumes more space than using an array because a map needs to maintain a red-black tree or a hash table, and it also requires hashing functions, which are time-consuming! The difference becomes apparent when dealing with large data volumes. Therefore, arrays are simpler, more direct, and effective!
Since the problem states that there are only lowercase letters, we can adopt a space-for-time hashing strategy. Use an array of length 26 to record the frequency of each letter in the magazine.
Then, use the ransomNote
to verify if this array contains all the letters needed for the ransomNote
.
Code
- Time complexity: O(n)
- Space complexity: O(1)
TypeScript
1 | function canConstruct(ransomNote: string, magazine: string): boolean { |
Conclusion
Another hash methods question, but use array would be the most efficiency way to do it. Always think the choice between array, set, and map, choose the most simple and efficient one!