Skip to content

Commit 5cc1753

Browse files
committed
Algorithm analysis log linear solution
1 parent a5cfed2 commit 5cc1753

File tree

2 files changed

+14
-15
lines changed

2 files changed

+14
-15
lines changed

analysis/anagrams-loglinear-solution.py

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,22 @@
11

2-
# O(n2)
2+
# O(nlogn)
33
def anagrams(string1: str, string2: str) -> bool:
44

5-
is_anagram: bool = True
5+
if len(string1) != len(string2):
6+
return False
67

8+
is_anagram: bool = True
9+
list1: list = list(string1)
710
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]:
2017
is_anagram = False
2118
else:
22-
pos1 += 1
19+
pos += 1
2320

2421
return is_anagram
2522

analysis/anagrams-quadratic-solution.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11

22
# O(n2)
33
def anagrams(string1: str, string2: str) -> bool:
4+
if len(string1) != len(string2):
5+
return False
46

57
is_anagram: bool = True
68

0 commit comments

Comments
 (0)