




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.
1var canConstruct = function(ransomNote, magazine) {
2    let count = {};
3    for (let char of magazine) {
4The solution uses a JavaScript object to count the frequency of each character in magazine. It checks if the object has enough of every character to construct ransomNote.
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)
public class Solution {
    public bool CanConstruct(string ransomNote, string magazine) {
        char[] ransomArray = ransomNote.ToCharArray();
        char[] magArray = magazine.ToCharArray();
        Array.Sort(ransomArray);
        Array.Sort(magArray);
        int i = 0, j = 0;
        while (i < ransomArray.Length && j < magArray.Length) {
            if (ransomArray[i] == magArray[j]) {
                i++;
            }
            j++;
        }
        return i == ransomArray.Length;
    }
}This C# solution involves sorting both character arrays of the input strings. It iteratively checks for every character in ransomNote if there is a corresponding character in magazine.