C# O(n) with Dictionary


  • 0
    H
    public IList<IList<string>> GroupAnagrams(string[] strs) {
            List<IList<string>> result = new List<IList<string>>();
            Dictionary<string, List<string>> map = new Dictionary<string, List<string>>();
            
            foreach(string str in strs) {
                char[] a = str.ToCharArray();
                Array.Sort(a);
                string norm = new string(a);
                if (!map.ContainsKey(norm)) map[norm] = new List<string>();
                map[norm].Add(str);
            }
            
            foreach(List<string> list in map.Values) result.Add(list);
            
            return result;
        }
    

  • 0
    E

    It's not O(n). It's n*(n + nlog(n)) which equals O(n^2*log(n))


Log in to reply
 

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