




Sponsored
Sponsored
This approach involves using hash maps to count the frequency of each letter in both ransomNote and magazine. The idea is to determine if magazine has enough of each letter to build ransomNote.
magazine.ransomNote and check if the magazine frequency is sufficient.ransomNote has a higher frequency than in magazine, return false.true.Time Complexity: O(m + n), where m and n are the lengths of magazine and ransomNote, respectively.
Space Complexity: O(1), as the space is allocated for a fixed-size frequency array.
1#include <unordered_map>
2#include <string>
3using namespace std;
4
5class Solution {
6public:
7    bool canConstruct(string ransomNote, string magazine) {
8        unordered_map<char, int> count;
9        for (char c : magazine) {
10            count[c]++;
11        }
12        for (char c : ransomNote) {
13            if (count[c]-- <= 0) {
14                return false;
            }
        }
        return true;
    }
};In this C++ solution, an unordered map is used to count character frequencies in magazine. As we traverse ransomNote, we decrease the count of each character. If we attempt to decrease a count that is already zero, we return false.
Instead of counting character frequencies, we can sort both ransomNote and magazine and use a two-pointer technique to check if magazine contains all letters needed for ransomNote in a sorted order.
ransomNote and magazine.ransomNote are matched, return true; otherwise, return false.Time Complexity: O(n log n + m log m), dominated by sorting
Space Complexity: O(1)
This Java solution uses arrays to hold character data for sorting. The two-pointer approach checks characters in sorted order, allowing us to confirm if ransomNote can be derived from magazine.