242-valid-anagram

Try it on leetcode

Description

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

 

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

 

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

 

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Solution(Python)

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        return self.match_by_unique_primeHash(s,t)
      
    # Time Complexity: O(n)
    # space complexity: O(n)
    def sort_and_match(self, s: str, t: str) -> bool:
        s = list(s)
        t = list(t)
        s.sort()
        t.sort()
        
        return len(s) == len(t) and s == t 
    
    # Time Complexity: O(n)
    # space complexity: O(k)
    def match_by_frequencyTable(self, s: str, t: str) -> bool:
        return Counter(s) == Counter(t)
    
    # Time Complexity: O(n)
    # space complexity: O(k)
    def match_by_unique_primeHash(self, s: str, t: str) -> bool:
        def primes(n):
            from itertools import count, islice
            primes = (n for n in count(2) if all(n % d for d in range(2, n)))
            return islice(primes, 0, n)
        def letters():
            return list(map(chr, range(97, 123)))
        def Uniqueprimehash(s):
            prime_hash = {
                key: val for key, val in zip(letters(), primes(26))
            }
            hash = 1
            for c in s:
                hash *= prime_hash[c]
            return hash
                
            
        return Uniqueprimehash(s) == Uniqueprimehash(t)