We should find all characters of the ransomNote in the magazine. So, we use two passes: (1) For the magazine, build {char -> count} map (2) For each char in ransomNote, we try finding it in magazine.
Say magazine has chars and
ransomNote has chars.
Time: , space:
.
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
mag = {}
for c in magazine:
mag[c] = mag.get(c, 0) + 1
for c in ransomNote:
if mag.get(c, 0) == 0:
return False
mag[c] -= 1
return True
Leave a comment