1 line Ruby/Python for Updated Problem
The problem just got updated, now asking for different results. Here are some solutions for the new version.\n\nAll of them use the sorted string as the group i
The problem just got updated, now asking for different results. Here are some solutions for the new version.\n\nAll of them use the sorted string as the group identifier, so for example the words "leetcoder" and "electrode" both have the group identifier "cdeeelort" (or rather an array version of it), which is how I know that they're anagrams of each other.\n\n---\n\n**Ruby solution 1**\n\nJust sort and group.\n\n    def group_anagrams(strs)\n      strs.sort.group_by { |s| s.chars.sort }.values\n    end\n\n---\n\n**Ruby solution 2**\n\nGroup first, then sort each group. Could be faster for big cases (though isn't for the OJ test cases).\n\n    def group_anagrams(strs)\n      strs.group_by { |s| s.chars.sort }.values.map(&:sort)\n    end\n\n---\n\n**Python solution 1**\n\nSort and group by group identifier, then sort each group normally.\n\n    def groupAnagrams(self, strs):\n        return [sorted(g) for _, g in itertools.groupby(sorted(strs, key=sorted), sorted)]\n\nOr "breaking it down" to maybe make it more readable for beginners and because I just noticed that in Firefox it violates my self-imposed *"no scrollbars"* rule (I usually use Chrome and didn't think it differed):\n\n    def groupAnagrams(self, strs):\n        groups = itertools.groupby(sorted(strs, key=sorted), sorted)\n        return [sorted(members) for _, members in groups]\n\n---\n\n**Python solution 2**\n\nUsing defaultdict to collect the groups.\n\n    def groupAnagrams(self, strs):\n        groups = collections.defaultdict(list)\n        for s in strs:\n            groups[tuple(sorted(s))].append(s)\n        return map(sorted, groups.values())
['Python', 'Ruby']