less than 1 minute read

Problem Statement

leetcode problem link

Solution [Accepted]

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        groups = defaultdict(list)
        for s in strs:
            key = tuple(sorted(list(s)))
            groups[key].append(s)

        return list(groups.values())
public class Solution {
    public IList<IList<string>> GroupAnagrams(string[] strs) {
        Dictionary<string, IList<string>> groups = new Dictionary<string, IList<string>>();
        foreach (string str in strs) {
            char[] chars = str.ToCharArray();
            chars.Sort();
            string key = new string(chars);
            Console.WriteLine(key);
            if (!groups.ContainsKey(key))
                groups[key] = new List<string>();
            groups[key].Add(str);
        }
        return groups.Values.ToList();
    }
}

Time: O(nklogk) Space: O(N*k)

Editorial

Approach 1: Categorize by Sorted String

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        ans = collections.defaultdict(list)
        for s in strs:
            ans[tuple(sorted(s))].append(s)
        return list(ans.values())
public class Solution {
    public IList<IList<string>> GroupAnagrams(string[] strs) {
        var dict = new Dictionary<string, List<string>>();
        foreach (var s in strs) {
            var ca = s.ToCharArray();
            Array.Sort(ca);
            var key = new String(ca);
            if (!dict.ContainsKey(key))
                dict[key] = new List<string>();
            dict[key].Add(s);
        }

        return new List<IList<string>>(dict.Values);
    }
}