Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

383. Ransom Note 🌟

Given two stings 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

same as is_subsequence problem.

O(N) Time O(N)=O(26) constant space

Code

class Solution{
public:
    bool canConstruct(string ransomNote, string magazine)    {
        vector<int> a(26, 0);
        for (auto &x : magazine)
            a[x - 'a']++;
        for (auto &x : ransomNote)        {
            if (--a[x - 'a'] < 0)
                return false;
        }
        return true;
    }
};