File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments