< Back




383. Ransom Note

Super easy question. Given a ransome note string and a magazine string, determine if the ransom note
can be constructed from the provided magazine. To solve this, we just count the characters'
occurrences in the ransom note and compare them to the characters' occurrences in the magazine.
If the occurrences of characters in the ransom note are less than or equal to the magazine's, we
verify that the ransom note can be constructed from the magazine.

The Python Counter class from the collections library is super useful for this task.

The solution is as follows:


  from collections import Counter
  class Solution:
      def canConstruct(self, ransomNote: str, magazine: str) -> bool:
          return Counter(ransomNote) <= Counter(magazine)


_ Time Complexity:

  O(max(n, m)) - We count every character in the ransom note and magazine strings.

_ Space Complexity:

  O(1) - We store the count of every character in the ransom note and magazine strings in a
  dictionary, however, the dictionary will have at most 26 characters, so the space complexity is
  constant.