File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ '''
2
+ # Leetcode 242. Valid Anagram
3
+
4
+ use `Counter` to (1)compare the frequency of characters in both strings, and (2)try to compare the frequency more efficiently. 🔍
5
+
6
+ ## Time and Space Complexity
7
+
8
+ ```
9
+ TC: O(n)
10
+ SC: O(n)
11
+ ```
12
+
13
+ ### A. use frequency object
14
+
15
+ #### TC is O(n):
16
+ - iterating through the strings just once to compare the frequency of characters. O(n)
17
+
18
+ #### SC is O(n):
19
+ - creating a new string `converted_s` to store the
20
+
21
+ ### B. use Counter more efficiently
22
+
23
+ #### TC is O(n):
24
+ - iterating through the strings just once to compare the frequency of characters. O(n)
25
+
26
+ #### SC is O(n):
27
+ - creating a new string `converted_s` to store the
28
+ '''
29
+ class Solution :
30
+ def isAnagramA (self , s : str , t : str ) -> bool :
31
+ if len (s ) != len (t ):
32
+ return False
33
+
34
+ frequency = Counter (s ) # SC: O(n)
35
+
36
+ for char in t : # TC: O(n)
37
+ if char not in frequency or frequency [char ] == 0 : # TC: O(1)
38
+ return False
39
+ frequency [char ] -= 1
40
+
41
+ return True
42
+
43
+ def isAnagramB (self , s : str , t : str ) -> bool :
44
+ return Counter (s ) == Counter (t ) # TC: O(n), SC: O(n)
You can’t perform that action at this time.
0 commit comments