Group anagrams c# Time limit exceeded ?


  • 0
    K

    public IList<IList<string>> GroupAnagrams(string[] strs) {
    var result = new List<IList<string>>();

        if(strs == null || strs.Length <= 0)
            return result; 
        
        if(strs.Length == 1)
        {
            result.Add(new List<string>() {strs[0]});
            return result;
        }
        
        Array.Sort(strs);
        Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
    
        foreach(var str in strs)
        {
            char[] c = str.ToCharArray();
            Array.Sort(c);
            string tempStr = new string(c);
            
            if (dict.ContainsKey(tempStr))
                dict[tempStr].Add(str);
            else
                dict.Add(tempStr, new List<string>() { str });
        }
    
        var keys = dict.Keys.ToList();
        keys.Sort();
        foreach (var key in keys)
        {
            result.Add(dict[key]);
        }
        
        return result;
    }

  • 0
    G

    I find that the C# times reported by the judge are generally 10x the time of the same algorithm in Java or other languages. This must be an artifact of whatever runtime they are using (mono?) - there is really no general perf difference between C# and Java in normal circumstances.

    The trivial solution to this problem (group strings by sorted version of string) is about 5 lines using Linq, but it times out and isn't accepted. It's very similar to an accepted python solution (and yours).


Log in to reply
 

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