Skip to content

Instantly share code, notes, and snippets.

@jones
Created September 2, 2015 23:55
Show Gist options
  • Save jones/98f37efc068423704a86 to your computer and use it in GitHub Desktop.
Save jones/98f37efc068423704a86 to your computer and use it in GitHub Desktop.
Given an array of strings, group anagrams together. For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"], Return: [ ["ate", "eat","tea"], ["nat","tan"], ["bat"] ] Note: For the return value, each inner list's elements must follow the lexicographic order. All inputs will be in lower-case.
class Solution(object):
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
from itertools import groupby
sortedAnagrams = sorted(sorted(strs), key=lambda a: sorted(a))
return [list(v) for k,v in groupby(sortedAnagrams, key=lambda a: sorted(a))]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment