Given two strings ransomNote and magazine, return True if ransomNote can be constructed from magazine and False otherwise.
Each letter in magazine can only be used once in ransomNote.
Example 1:
Input: ransomNote = "aa", magazine = "abb" Output: False
Example 2:
Input: ransomNote = "aa", magazine = "aab" Output: True
Note:
Your algorithm should run in O(n + m) time and use O(Σ) extra space.
Hints:
Let's take the two examples given in the statement and solve them "by hand". In both examples,
ransomNote consists of two 'a's. Which means we need to have at least two 'a's in magazine to be able to construct the solution.
In the first example, we have only one 'a' in magazine and that's why we return False while in the second example, we have two of them, so that's why we return True.
Pretty simple. Now what if ransomNote also contains letter 'b'? What property should be satisfied to return True? Take some small examples on paper and try to figure it out.
Let's take
ransomNote = "abba". We need at least two 'a's and two 'b's in magazine to be able to construct the solution. First observation is that the order of letters in ransomNote is not important. The requirement is the same also for ransomNote = "aabb" or ransomNote = "abba".
The same holds true for magazine. It doesn't matter if magazine = "aaabbb" or magazine = "ababab", both are good as the conditions are satisfied:
- 'a' occurs in
magazineat least the same number of times it does inransomNote(3 >= 2) - 'b' occurs in
magazineat least the same number of times it does inransomNote(3 >= 2)
True for the general case?
The condition is that for each letter of the alphabet (from 'a' to 'z'), the letter should appear in
magazine at least the same number of times it does in ransomNote.
So we need to separately count the number of occurrences of each letter in magazine and in ransomNote. How can we achieve this?
We have a data structure specially designed to do that: a frequency table, such as a Hash Map (or, since the letters are only 'a' to 'z', a 26-slot array). We can build two frequency tables:
- one for
ransomNote, where the entry for lettercis the number of occurrences ofcinransomNote - one for
magazine, where the entry for lettercis the number of occurrences ofcinmagazine
Using a loop, we will go through every character
c of ransomNote and increment the entry for c in its table.
We will do the same for magazine.
What should we do after we have populated these tables?
Using a loop, we should go through each character
c of the alphabet (from 'a' to 'z') and check if the count of c in ransomNote is greater than its count in magazine. If so, we should return False.
When this loop terminates, we can conclude that the solution is valid, so we can return True
Walkthroughs of the solution. Try the steps first, then watch to compare approaches.
Free plan: 30 tutor messages. PRO is unlimited.
Saved
Ctrl + Enter to check
