Skip to content

383. Ransom Note 👍

  • Time: $O(|\texttt{ransomNote}| + |\texttt{magazine}|)$
  • Space: $O(128) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  bool canConstruct(string ransomNote, string magazine) {
    vector<int> count(128);

    for (const char c : magazine)
      ++count[c];

    for (const char c : ransomNote)
      if (--count[c] < 0)
        return false;

    return true;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public boolean canConstruct(String ransomNote, String magazine) {
    int[] count = new int[128];

    for (final char c : magazine.toCharArray())
      ++count[c];

    for (final char c : ransomNote.toCharArray())
      if (--count[c] < 0)
        return false;

    return true;
  }
}
1
2
3
4
5
class Solution:
  def canConstruct(self, ransomNote: str, magazine: str) -> bool:
    count1 = Counter(ransomNote)
    count2 = Counter(magazine)
    return all(count1[c] <= count2[c] for c in string.ascii_lowercase)