Skip to content

Commit 1b0b0b1

Browse files
committed
add rivkode valid-anagram
1 parent 32d80da commit 1b0b0b1

File tree

1 file changed

+50
-10
lines changed

1 file changed

+50
-10
lines changed

valid-anagram/rivkode.py

Lines changed: 50 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,66 @@
11
from typing import List
22

33
# Time Complexity O(n log n)
4-
# - when sorting by sorted function(TimSort) for each string it takes O(nlogn)
5-
# - traversing for loop takes O(n)
4+
# - check len first
5+
# - make set for one of list for each values
6+
# - if there's a duplication, then value += 1. This is a number of count.
7+
# - fetch value using set.get() method.
8+
# - minus 1 and check if it is less than 0 which means it's invalid. return false directly.
69
# Space Complexity O(n)
710
# - when sorting takes O(n)
811

912
class Solution:
1013
def isAnagram(self, s: str, t: str) -> bool:
11-
s_sorted = sorted(s)
12-
t_sorted = sorted(t)
1314

14-
for i in range(len(s_sorted)):
15-
if s_sorted[i] != t_sorted[i]:
16-
return False
17-
return True
15+
"""
16+
:type s: str
17+
:type t: str
18+
:rtype: bool
19+
"""
20+
s_list = list(s)
21+
t_list = list(t)
22+
23+
if len(s_list) != len(t_list):
24+
return False
25+
26+
t_set = {}
27+
for t_val in t_list:
28+
cur = t_set.get(t_val, 0)
29+
cur += 1
30+
t_set[t_val] = cur
31+
32+
33+
flag = True
34+
35+
for s_val in s_list:
36+
if t_set.get(s_val):
37+
cur = t_set.get(s_val)
38+
cur -= 1
39+
t_set[s_val] = cur
40+
if cur < 0:
41+
flag = False
42+
break
43+
else:
44+
flag = False
45+
break
46+
47+
return flag
48+
49+
# previous logic
50+
# s_sorted = sorted(s)
51+
# t_sorted = sorted(t)
52+
53+
# for i in range(len(s_sorted)):
54+
# if s_sorted[i] != t_sorted[i]:
55+
# return False
56+
# return True
57+
1858

1959
if __name__ == "__main__":
2060
solution = Solution()
2161

22-
s = "nagaram"
23-
t = "anagram"
62+
s = "a"
63+
t = "ab"
2464

2565
result = solution.isAnagram(s, t)
2666
print(result)

0 commit comments

Comments
 (0)