-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidAnagramDay17.py
More file actions
59 lines (41 loc) · 1.15 KB
/
Copy pathValidAnagramDay17.py
File metadata and controls
59 lines (41 loc) · 1.15 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
47
48
49
50
51
52
53
54
55
56
57
58
59
#Brute Force Approach
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return sorted(s) == sorted(t)
# Time Complexity:
# Sorting takes O(n log n), where n = len(s) or len(t)
#
# Space Complexity:
# O(n) for storing sorted lists
# we can do like this also
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
# Better Approach
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
if len(s) != len(t):
return False
count_s = {}
count_t = {}
for char in s:
count_s[char] = count_s.get(char, 0) + 1
for char in t:
count_t[char] = count_t.get(char, 0) + 1
return count_s == count_t
# TC - O(n)
# SC - O(n)
#Optimal Approach
from collections import Counter
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
count_s = Counter(s)
for char in t:
if char not in count_s:
return False
count_s[char] -= 1
if count_s[char] == 0:
del count_s[char]
return len(count_s) == 0
# TC - O(n)
# SC - O(1)