O(n) time, O(1) space solution, no hashing


  • 0
    E

    The core insight here is that we can count the letters in s and t, and if they're a match, they will be anagrams of each other.
    A secondary insight is that since we're restricted to lowercase English letters, we don't need a hashmap and can store the letter counts in an array.

        def isAnagram(self, s, t):
            letters = [0 for i in range(26)]
            sub = ord('a')
            for x in s:
                letters[ord(x)-sub] += 1
            for y in t:
                letters[ord(y)-sub] -= 1
            return sum(count==0 for count in letters)==26```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.