File tree Expand file tree Collapse file tree 2 files changed +14
-15
lines changed Expand file tree Collapse file tree 2 files changed +14
-15
lines changed Original file line number Diff line number Diff line change 1
1
2
- # O(n2 )
2
+ # O(nlogn )
3
3
def anagrams (string1 : str , string2 : str ) -> bool :
4
4
5
- is_anagram : bool = True
5
+ if len (string1 ) != len (string2 ):
6
+ return False
6
7
8
+ is_anagram : bool = True
9
+ list1 : list = list (string1 )
7
10
list2 : list = list (string2 )
8
- pos1 : int = 0
9
- while pos1 < len (string1 ) and is_anagram :
10
- character = string1 [pos1 ]
11
- character_found : bool = False
12
- pos2 : int = 0
13
- while pos2 < len (list2 ) and not character_found :
14
- if list2 [pos2 ] == character :
15
- list2 [pos2 ] = None
16
- character_found = True
17
- else :
18
- pos2 += 1
19
- if not character_found :
11
+ list1 .sort () # sorting is O(nlogn)
12
+ list2 .sort () # sorting is O(nlogn)
13
+ pos : int = 0
14
+ # loop is O(n)
15
+ while pos < len (list1 ) and is_anagram :
16
+ if list1 [pos ] != list2 [pos ]:
20
17
is_anagram = False
21
18
else :
22
- pos1 += 1
19
+ pos += 1
23
20
24
21
return is_anagram
25
22
Original file line number Diff line number Diff line change 1
1
2
2
# O(n2)
3
3
def anagrams (string1 : str , string2 : str ) -> bool :
4
+ if len (string1 ) != len (string2 ):
5
+ return False
4
6
5
7
is_anagram : bool = True
6
8
You can’t perform that action at this time.
0 commit comments