Skip to content

Commit 9ac94c0

Browse files
authored
Improve checking anagrams in O(n) with dictionary (TheAlgorithms#4806)
1 parent 13fdf21 commit 9ac94c0

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

strings/check_anagrams.py

+25-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""
22
wiki: https://en.wikipedia.org/wiki/Anagram
33
"""
4+
from collections import defaultdict
45

56

67
def check_anagrams(first_str: str, second_str: str) -> bool:
@@ -16,10 +17,30 @@ def check_anagrams(first_str: str, second_str: str) -> bool:
1617
>>> check_anagrams('There', 'Their')
1718
False
1819
"""
19-
return (
20-
"".join(sorted(first_str.lower())).strip()
21-
== "".join(sorted(second_str.lower())).strip()
22-
)
20+
first_str = first_str.lower().strip()
21+
second_str = second_str.lower().strip()
22+
23+
# Remove whitespace
24+
first_str = first_str.replace(" ", "")
25+
second_str = second_str.replace(" ", "")
26+
27+
# Strings of different lengths are not anagrams
28+
if len(first_str) != len(second_str):
29+
return False
30+
31+
# Default values for count should be 0
32+
count = defaultdict(int)
33+
34+
# For each character in input strings,
35+
# increment count in the corresponding
36+
for i in range(len(first_str)):
37+
count[first_str[i]] += 1
38+
count[second_str[i]] -= 1
39+
40+
for _count in count.values():
41+
if _count != 0:
42+
return False
43+
return True
2344

2445

2546
if __name__ == "__main__":

0 commit comments

Comments
 (0)