Sunday, June 2, 2024

[LeetCode] Ransom Note

Problem: Given two strings ransomNote and magazine, return true if ransomNote can be constructed by using the letters from magazine and false otherwise.

Each letter in magazine can only be used once in ransomNote.

Example:

Input: ransomNote = "a", magazine = "b"
Output: false
Input: ransomNote = "aa", magazine = "ab"
Output: false
Input: ransomNote = "aa", magazine = "aab"
Output: true


Approach: It's a simple problem to solve. We can use hash map to solve this problem. Have a look at the implementation.


Implementation in C#:

    public bool CanConstruct(string ransomNote, string magazine)
    {
        int[] magazineMap = new int[26];
        foreach (char ch in magazine)
        {
            ++magazineMap[ch - 'a'];
        }
        foreach (char ch in ransomNote)
        {
            if (magazineMap[ch - 'a'] == 0)
            {
                return false;
            }
            --magazineMap[ch - 'a'];
        }
        return true;
    }


Complexity: O(n)

No comments:

Post a Comment