Question
What is wrong in my solution for Leetcode's RansomNote
I am working on the Leetcode problem 383. Ransom Note:
Given two strings
ransomNote
andmagazine
, returntrue
ifransomNote
can be constructed by using the letters frommagazine
andfalse
otherwise.Each letter in
magazine
can only be used once inransomNote
.
My code passes 98 out of 128 testcases. I created two dictionaries with counts of each occurrence, and wrote some code to compare the two counts.
Here is what I have:
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransomdict = {}
magadict = {}
for i in ransomNote:
if i in ransomdict:
ransomdict[i] +=1
else:
ransomdict[i] = 1
for j in magazine:
if j in magadict:
magadict[j] +=1
else:
magadict[j] = 1
print(ransomdict)
print(magadict)
for k in ransomdict:
if k in magadict:
if magadict[k] >= ransomdict[k]:
return True
else:
return False
The following test case is supposed to return False
, but it is returning True
:
ransomNote = "abb"
magazine = "ab"
To debug, I printed ransomdict
and magadict
, and clearly the counts are right. What is my mistake?
I know this code isn't optimized; I'm just looking for a way to fix what I am missing here and successfully pass all test cases.