Ransom Note

Solution For Ransom Note

Problem:

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:

Input: ransomNote = “aa”, magazine = “aab”
Output: true

Input: ransomNote = “aaa”, magazine = “aab”
Output: false

Solution:

To solve this problem, we can use a HashMap to store the frequency of each character in the magazine string. Then, we can iterate through the ransomNote string and check if each character exists in the HashMap and if its frequency is greater than 0. If it is, we decrement its frequency and move on to the next character in the ransomNote string. If a character does not exist in the HashMap or its frequency is 0, we return false. Otherwise, we return true at the end of the iteration.

Here’s the detailed implementation of our solution:

class Solution {
public boolean canConstruct(String ransomNote, String magazine) {
HashMap map = new HashMap<>();
for(char c : magazine.toCharArray()){
map.put(c, map.getOrDefault(c, 0) + 1);
}
for(char c : ransomNote.toCharArray()){
if(!map.containsKey(c) || map.get(c) == 0){
return false;
}else{
map.put(c, map.get(c) – 1);
}
}
return true;
}
}

Here, we first create a HashMap called map to store the frequency of each character in the magazine string. We iterate through each character in the magazine string and add its frequency to the map using getOrDefault() method. This helps us keep track of the frequency of each character.

Next, we iterate through each character in the ransomNote string and check if it exists in the map and if its frequency is greater than 0. If it is, we decrement its frequency in the map using map.get(c) – 1 and move on to the next character in the ransomNote string. If it does not exist in the map or its frequency is 0, we immediately return false. If we reach the end of the iteration without any issues, we return true.

The time complexity of this solution is O(n) where n is the length of the ransomNote string, since we iterate through each character in both the ransomNote and the magazine strings. The space complexity is also O(n) where n is the length of the magazine string, since we store each character’s frequency in the map.

Step by Step Implementation For Ransom Note

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        // create a hashmap to store the count of each character in the magazine
        HashMap map = new HashMap<>();
        for(int i = 0; i < magazine.length(); i++){
            char c = magazine.charAt(i);
            if(!map.containsKey(c)){
                map.put(c, 1);
            }else{
                map.put(c, map.get(c) + 1);
            }
        }
        
        // check if the ransom note can be constructed from the magazine
        for(int i = 0; i < ransomNote.length(); i++){
            char c = ransomNote.charAt(i);
            if(!map.containsKey(c) || map.get(c) == 0){
                return false;
            }else{
                map.put(c, map.get(c) - 1);
            }
        }
        return true;
    }
}
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
    
    #Create a hashmap to store the count of each character in the magazine
    hashmap = {}
    
    for char in magazine:
        if char not in hashmap:
            hashmap[char] = 1
        else:
            hashmap[char] += 1
    
    #Now, check if the ransom note can be made using the characters in the magazine
    for char in ransomNote:
        if char not in hashmap or hashmap[char] == 0:
            return False
        else:
            hashmap[char] -= 1
    
    #If we reach this point, it means that all the characters in the ransom note are present in the magazine
    return True
var canConstruct = function(ransomNote, magazine) {
    // create a hashmap to store the counts of each character in the magazine
    const magazineCharCounts = {};
    for (let i = 0; i < magazine.length; i++) {
        const char = magazine[i];
        // if the character is not in the hashmap, set its count to 1
        if (!(char in magazineCharCounts)) {
            magazineCharCounts[char] = 1;
        // otherwise, increment its count
        } else {
            magazineCharCounts[char]++;
        }
    }
    
    // iterate through the ransom note,
    // and check if each character can be found in the hashmap
    // with a sufficient quantity
    for (let i = 0; i < ransomNote.length; i++) {
        const char = ransomNote[i];
        // if the character is not in the hashmap, or
        // if the character is in the hashmap but with a count of 0,
        // then we know we can't construct the ransom note
        if (!(char in magazineCharCounts) || magazineCharCounts[char] === 0) {
            return false;
        }
        // otherwise, we can use this character, so we decrement the count
        magazineCharCounts[char]--;
    }
    // if we've gotten through the whole ransom note and haven't returned false,
    // then we can construct the ransom note
    return true;
};
class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        // create a map to store the character counts for the ransom note
        unordered_map map;
        for (char c : ransomNote) {
            if (map.find(c) == map.end()) {
                map[c] = 1;
            } else {
                map[c]++;
            }
        }
        
        // go through the characters in the magazine
        // if a character in the magazine exists in the map, decrement its count
        // if a character in the magazine does not exist in the map, or if its count is 0, move on
        for (char c : magazine) {
            if (map.find(c) != map.end() && map[c] > 0) {
                map[c]--;
            }
        }
        
        // go through the map
        // if any character has a count greater than 0, return false
        // otherwise, return true
        for (auto it = map.begin(); it != map.end(); it++) {
            if (it->second > 0) {
                return false;
            }
        }
        return true;
    }
};
using System; 

public class Solution {
    public bool CanConstruct(string ransomNote, string magazine) {
        // check if the ransom note can be constructed from the letters in the magazine
        // using the available letters
        
        // create a hashmap to keep track of the number of each letter in the magazine
        var map = new Dictionary();
        
        // fill the hashmap
        for(int i = 0; i < magazine.Length; i++)
        {
            if(!map.ContainsKey(magazine[i]))
            {
                map.Add(magazine[i], 1);
            }
            else
            {
                map[magazine[i]]++;
            }
        }
        
        // check if the ransom note can be constructed from the letters in the hashmap
        for(int i = 0; i < ransomNote.Length; i++)
        {
            if(!map.ContainsKey(ransomNote[i]) || map[ransomNote[i]] == 0)
            {
                return false;
            }
            else
            {
                map[ransomNote[i]]--;
            }
        }
        return true;
    }
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]