-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRansome_Note_Day30.py
More file actions
46 lines (36 loc) · 1.03 KB
/
Ransome_Note_Day30.py
File metadata and controls
46 lines (36 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#Brute Approach
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
magazine = list(magazine)
for ch in ransomNote:
if ch in magazine:
magazine.remove(ch)
else:
return False
return True
# TC - O(n* m)
# SC - O(m)
#Better Approach
from collections import Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransom_count = Counter(ransomNote)
magazine_count = Counter(magazine)
for ch in ransom_count:
if ransom_count[ch] > magazine_count.get(ch, 0):
return False
return True
# TC - O(n + m)
# SC - O(1)
#Optimal Approach
from collections import Counter
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
count = Counter(magazine)
for ch in ransomNote:
if count[ch] == 0:
return False
count[ch] -= 1
return True
# TC - O(m+n)
# SC - O(1)