Skip to content

Commit 9b43181

Browse files
authored
Merge pull request #727 from yolophg/main
[Helena] Week 2
2 parents 65e5f8c + 87ae446 commit 9b43181

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

valid-anagram/yolophg.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time Complexity: O(n)
2+
# Go through both strings once to count and compare characters.
3+
4+
# Space Complexity: O(1)
5+
# The dictionary stores at most 26 letters, so space usage is constant.
6+
7+
class Solution:
8+
def isAnagram(self, s: str, t: str) -> bool:
9+
char_count = {}
10+
11+
# count frequencies of characters in string s
12+
for char in s:
13+
if char in char_count:
14+
char_count[char] += 1
15+
else:
16+
char_count[char] = 1
17+
18+
# go through 't' and decrease the count
19+
for char in t:
20+
# if the character isn't in the dictionary, it's not an anagram
21+
if char in char_count:
22+
char_count[char] -= 1
23+
else:
24+
return False
25+
26+
# check if all the counts are zero
27+
for val in char_count.values():
28+
if val != 0:
29+
return False
30+
31+
return True

0 commit comments

Comments
 (0)