Use Awesome prime numbers * product of unique prime numbers is unique * ( PYTHON )


  • 0
    A
    class Solution:
        def groupAnagrams(self, strs):
            """
            :type strs: List[str]
            :rtype: List[List[str]]
            """
            # Use prime number property
            # product of unique product numbers is unique
            # assign each char to unique prime number
            # There is you go, so eat ate will result in same product 
            prime_numbers = [ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101]
            prime_values = {}
            for string in strs:
                prime = 1
                for char in string:
                    prime = prime*prime_numbers[ord(char)-97]
                    
                if(prime not in prime_values.keys()):
                    prime_values[prime] = [string]
                else:
                    prime_values[prime].append(string)
                    
            return(list(prime_values.values()))
    

Log in to reply
 

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