383. Ransom Note

Dare2Solve

Dare2Solve

383. Ransom Note
SAMSUNG 49-Inch Odyssey G9
SAMSUNG 49-Inch Odyssey G9
Because earth is not flat

Intuition

The problem requires determining if we can construct the ransomNote string using the letters available in the magazine string. Each letter in the magazine can only be used once. This means we need to ensure that for each character in ransomNote, there is a corresponding character in magazine that hasn't been used already.

Approach

  1. Count Characters in magazine:

    Use a dictionary to count the occurrences of each character in magazine.

  2. Check Characters in ransomNote:

    Iterate through each character in ransomNote and check if it is present in the dictionary with a non-zero count.

    • If the character is present and its count is greater than zero, decrement the count.

    • If the character is not present or its count is zero, return false.

  3. Return true:

    If all characters in ransomNote can be matched with characters in magazine, return true.

This approach ensures that we efficiently check the availability of each character in ransomNote against magazine.

Complexity

Time Complexity

Space Complexity

Code

C++

class Solution {
public:
    bool canConstruct(string ransomNote, string magazine) {
        for (char c : magazine) {
            size_t pos = ransomNote.find(c);
            if (pos != string::npos) {
                ransomNote.erase(pos, 1);
            }
        }
        return ransomNote.empty();
    }
};

Python

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        for char in magazine:
            ransomNote = ransomNote.replace(char, '', 1)
        return ransomNote == ''

Java

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        for (char c : magazine.toCharArray()) {
            ransomNote = ransomNote.replaceFirst(String.valueOf(c), "");
        }
        return ransomNote.isEmpty();
    }
}

JavaScript

var canConstruct = function (ransomNote, magazine)
{
    for (const char of magazine) 
    {
        ransomNote = ransomNote.replace(char, "");
    }
    if (!ransomNote) return true;
    else return false;
};