LeetCode Solutions

383. Ransom Note

Time: $O(|\texttt{ransomNote}| + |\texttt{magazine}|)$

Space: $O(128) = O(1)$

			

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;
  }
};
			

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;
  }
}
			

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)