383. Ransom Note

1. Description

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.

2. Example

Example 1

Input: ransomNote = “a”, magazine = “b”
Output: false

Example 2

Input: ransomNote = “aa”, magazine = “ab”
Output: false

Example 3

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

3. Constraints

  • 1 <= ransomNote.length, magazine.length <= $10^5$
  • ransomNote and magazine consist of lowercase English letters.

4. Solutions

Hash Table

n = magazine.size()
Time complexity: O(n)
Space complexity: O(1)

class Solution {
public:
    bool canConstruct(const string &ransomNote, const string &magazine) {
        const int m = ransomNote.size(), n = magazine.size();
        array<int, 26> letter_count{};
        for (int i = 0; i < n; ++i) {
            ++letter_count[index(magazine[i])];
        }

        for (int i = 0; i < m; ++i) {
            --letter_count[index(ransomNote[i])];
            if (letter_count[index(ransomNote[i])] < 0) {
                return false;
            }
        }

        return true;
    }

private:
    static int index(char letter) {
        return letter - 'a';
    }
};
Last updated:
Tags: String
comments powered by Disqus