Skip to content

Commit 6bccbb4

Browse files
committed
valid anagram solution
1 parent 571311f commit 6bccbb4

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

valid-anagram/jungsiroo.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def isAnagram(self, s: str, t: str) -> bool:
3+
if len(s) != len(t):
4+
return False
5+
6+
# sort and compare
7+
# Tc : O(nlogn) / Sc : O(n)(Because of python timsort)
8+
"""
9+
s = sorted(s)
10+
t = sorted(t)
11+
for s_char, t_char in zip(s, t):
12+
if s_char != t_char:
13+
return False
14+
return True
15+
"""
16+
17+
# dictionary to count letters
18+
# Tc : O(n) / Sc : O(n)
19+
letters_cnt = dict()
20+
INF = int(1e6)
21+
for s_char in s:
22+
letters_cnt[s_char] = letters_cnt.get(s_char,0)+1
23+
24+
for t_char in t:
25+
letters_cnt[t_char] = letters_cnt.get(t_char,INF)-1
26+
if letters_cnt[t_char] < 0:
27+
return False
28+
29+
return sum(letters_cnt.values()) == 0
30+

0 commit comments

Comments
 (0)