Home > database >  How can I get my desired output for this code? Time Limit Exceeded
How can I get my desired output for this code? Time Limit Exceeded

Time:04-25

code-->

class Solution:
    def isAnagram(self, s1: str,t1: str) -> bool:
        flag=1
        s = list(s1)
        t = list(t1)
        for i in range(len(s)):
            for j in range(len(s)):
                if s[i]==t[j]:
                    s[i]=t[j]='0'
                    break
        for i in range(len(s)):
            if s[i] !='0' :
                flag=0
                break
        if flag:
          print(True)
        else:
          print(False)          

Constraints:

1 <= s.length, t.length <= 5 * 104

Please someone help to fix this code.

CodePudding user response:

You could utilize the fact that two anagrams when sorted will be the same:

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return sorted(s) == sorted(t)

Or that they would have the same counts of characters:

from collections import Counter

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return Counter(s) == Counter(t)

The latter is more efficient since sorting is O(n log n), while constructing the Counter/Dictionary/Map/HashTable is linear time i.e., O(n).


If you don't want to use collections.Counter since it feels like it's abstracting away the core part of the problem, you could replicate its functionality with a list (assumes both strings will only contain lowercase characters):

class Solution:
    def lowercase_counts(self, s: str) -> list[int]:
        counts = [0] * 26
        for ch in s:
            counts[ord(ch) - ord('a')]  = 1
        return counts
    
    def isAnagram(self, s: str, t: str) -> bool:
        return self.lowercase_counts(s) == self.lowercase_counts(t)

Or more robustly supporting all Unicode characters using a dictionary:

class Solution:
    def character_counts(self, s: str) -> dict[str, int]:
        counts = {}
        for ch in s:
            counts[ch] = counts.get(ch, 0)   1
        return counts
    
    def isAnagram(self, s: str, t: str) -> bool:
        return self.character_counts(s) == self.character_counts(t)

CodePudding user response:

Simply use a Counter.

from collections import Counter

def is_anagram(s1:str, s2:str) -> bool:
    return Counter(s1) == Counter(s2)

  • Related