

Counterclass Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
return Counter(ransomNote) <= Counter(magazine)
cnt as the inventory (multiset) of characters in magazineransomNote, decrement cnt[ch] for each charFalse immediatelyTrueclass Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
# Optional
if len(ransomNote) > len(magazine):
return False
cnt = {}
for ch in magazine:
cnt[ch] = cnt.get(ch, 0) + 1
for ch in ransomNote:
cnt[ch] = cnt.get(ch, 0) - 1
if cnt[ch] < 0:
return False
return True
Time Complexity: where n = len(magazine), m = len(ransomNote)
Space Complexity: where u is the number of distinct chars in magazine