Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Group anagrams challenge

Sharing is caring!

Problem statement
Given an array of strings, group anagrams together.

Sample input

["eat", "tea", "tan", "ate", "nat", "bat"]

Sample output

  ["ate", "eat","tea"],

Note: All inputs will be in lower-case.

Full code

class Solution(object):
    def groupAnagrams(self, strs):
        :type strs: List[str]
        :rtype: List[List[str]]
        map = {}
        for w in strs:
            key = ''.join(sorted(w))
            if not key in map:
                map[key] = []
        return map.values()

def main():
    solution = Solution()
    print(solution.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]))

if __name__ == "__main__": main()