Any python suggestions?


  • 0
    S

    I am writing my code in python and I am wondering if there is any way to improve the time complexity of the algorithm.

    class Solution:
    # @param strs, a list of strings
    # @return a list of strings
    def anagrams(self, strs):
        ana_set = {}
        result = set()
        for item in strs:
            key = sorted(item)
            if key in ana_set.keys():
                result.add(item)
                if ana_set[key]:
                    result.add(ana_set[key])
                    ana_set[key] = None
            else:
                ana_set[str(key)] = item
        return list(result)

  • 0
    S

    Have you actually gotten this accepted? By key = sorted(item), so you would need check it with if str(key) in ana_set: and it looks you would only need a set instead of a dict for ana_set.

    I don't see why you would do this ana_set[key] = None. I think there could be multiple strs to be anagrams of each other.


  • 0
    S

    To improve, you may count the number of unique characters in a str and sort by those unique characters instead of the entire str. Sorting unique characters runs in consistent time as there are at most 26 unique ones, while sorting the str does not.


Log in to reply
 

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