Skip to content

Improve checking anagrams in O(n) with dictionary #4806

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 31, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 25 additions & 4 deletions strings/check_anagrams.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
wiki: https://en.wikipedia.org/wiki/Anagram
"""
from collections import defaultdict


def check_anagrams(first_str: str, second_str: str) -> bool:
Expand All @@ -16,10 +17,30 @@ def check_anagrams(first_str: str, second_str: str) -> bool:
>>> check_anagrams('There', 'Their')
False
"""
return (
"".join(sorted(first_str.lower())).strip()
== "".join(sorted(second_str.lower())).strip()
)
first_str = first_str.lower().strip()
second_str = second_str.lower().strip()

# Remove whitespace
first_str = first_str.replace(" ", "")
second_str = second_str.replace(" ", "")

# Strings of different lengths are not anagrams
if len(first_str) != len(second_str):
return False

# Default values for count should be 0
count = defaultdict(int)

# For each character in input strings,
# increment count in the corresponding
for i in range(len(first_str)):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very cool!


Sema Reaction: 🏆 This code is awesome | Sema Tags: Efficient

count[first_str[i]] += 1
count[second_str[i]] -= 1

for _count in count.values():
if _count != 0:
return False
return True


if __name__ == "__main__":
Expand Down