Ransom Note easy
Problem Statement
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 = "a", magazine = "b" Output: false
Example 2
Input: ransomNote = "aa", magazine = "ab" Output: false
Example 3
Input: ransomNote = "aa", magazine = "aab" Output: true
Steps
-
Create a character frequency map for the
magazine
string: We'll use a JavaScript object (or Map in other languages) to store the count of each character in themagazine
. -
Iterate through the
ransomNote
string: For each character inransomNote
, check if it exists as a key in the frequency map. -
Check frequency: If the character exists, check if its count is greater than 0. If it is, decrement the count. If the character doesn't exist or its count is 0, it means we can't construct the
ransomNote
and we returnfalse
. -
Return
true
: If we successfully iterate through the entireransomNote
without finding any missing or insufficient characters, it means we can construct theransomNote
frommagazine
, so we returntrue
.
Explanation
The core idea is to efficiently check if the ransomNote
can be formed using the characters available in the magazine
. Using a frequency map allows for constant-time (O(1)
) lookups and updates of character counts, which optimizes the overall time complexity.
Code (TypeScript)
function canConstruct(ransomNote: string, magazine: string): boolean {
const magazineCharCount: { [key: string]: number } = {};
// Create frequency map for magazine
for (const char of magazine) {
magazineCharCount[char] = (magazineCharCount[char] || 0) + 1;
}
// Check if ransomNote can be constructed
for (const char of ransomNote) {
if (!magazineCharCount[char] || magazineCharCount[char] === 0) {
return false; // Character not found or count is zero
}
magazineCharCount[char]--;
}
return true; // Ransom note can be constructed
}
// Example usage
console.log(canConstruct("a", "b")); // false
console.log(canConstruct("aa", "aab")); // true
console.log(canConstruct("aa", "ab")); // false
Complexity
- Time Complexity: O(m + n), where m is the length of
ransomNote
and n is the length ofmagazine
. We iterate through both strings once. - Space Complexity: O(k), where k is the number of unique characters in
magazine
. The space used is proportional to the size of the frequency map. In the worst case, k could be equal to n (length of magazine), but often it will be smaller.