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
.
ransomNote
and magazine
consist of lowercase English letters only.ransomNote
or magazine
is empty?
ransomNote
is empty, the return value should be true
because an empty note can always be constructed.magazine
is empty and ransomNote
is not, the return value should be false
.magazine
using an array or a hash map.ransomNote
and decrease the frequency count from the magazine’s frequency map.magazine
goes below zero, return false
.ransomNote
can be matched with characters in magazine
, return true
.magazine
will take O(m)
time where m
is the length of magazine
.ransomNote
against the frequency map will take O(n)
time where n
is the length of ransomNote
.O(m + n)
.#include <iostream>
#include <unordered_map>
#include <string>
bool canConstruct(std::string ransomNote, std::string magazine) {
std::unordered_map<char, int> letterCount;
// Build the letter frequency map from the magazine
for (char c : magazine) {
letterCount[c]++;
}
// Check if ransom note can be constructed
for (char c : ransomNote) {
if (letterCount[c] == 0) {
return false;
}
letterCount[c]--;
}
return true;
}
int main() {
std::string ransomNote = "a";
std::string magazine = "b";
std::cout << std::boolalpha << canConstruct(ransomNote, magazine) << std::endl; // Output: false
ransomNote = "aa";
magazine = "ab";
std::cout << std::boolalpha << canConstruct(ransomNote, magazine) << std::endl; // Output: false
ransomNote = "aa";
magazine = "aab";
std::cout << std::boolalpha << canConstruct(ransomNote, magazine) << std::endl; // Output: true
return 0;
}
This code implements the described strategy to determine if the ransomNote
can be constructed from the magazine
. It uses an unordered map to keep track of the character count in the magazine and then checks if those counts suffice to form the ransom note.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?