From 20577bcdd86d79e45f4a9d594de9f7fe8467c489 Mon Sep 17 00:00:00 2001 From: Swayam Prakash Sahu <91021799+SwayamSahu@users.noreply.github.com> Date: Mon, 31 Oct 2022 23:48:48 +0530 Subject: [PATCH] Refactored the code to reduce time complexity The time complexity now is O(n), which was O(nlogn) with the earlier method. --- algorithms/strings/anagram_check.py | 31 ++++++++++++++++------------- 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/algorithms/strings/anagram_check.py b/algorithms/strings/anagram_check.py index 5c20128..7627400 100644 --- a/algorithms/strings/anagram_check.py +++ b/algorithms/strings/anagram_check.py @@ -1,14 +1,17 @@ -# function to check if two strings are -# anagram or not -def check(s1, s2): - - # the sorted strings are checked - if(sorted(s1)== sorted(s2)): - print("The strings are anagrams.") - else: - print("The strings aren't anagrams.") - -# driver code -s1 ="listen" #String 1 -s2 ="silent" #String 2 -check(s1, s2) \ No newline at end of file +from collections import Counter + +# function to check if two strings are +# anagram or not +def check(s1, s2): + + # implementing counter function + if(Counter(s1) == Counter(s2)): + print("The strings are anagrams.") + else: + print("The strings aren't anagrams.") + + +# driver code +s1 = "listen" +s2 = "silent" +check(s1, s2)
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: