Group Anagrams


  • 0

    Click here to see the full article post


  • 0
    D

    Good article @awice.
    Hope Leetcode releases many more articles to come!


  • 0

    Is it required to provide Java solutions for these articles? This is the first time I have ever seen Python solution in an article.


  • 0
    A

    Not sure why you need to append # in the key ? seems the key would be unique without that also ?


  • 1
    R

    @AmanJsAneja1989
    The keys will not be unique if no delimiter is used for example say a string is "ab" where a occurs 12 times and b occurs 1 times so the string is 121 and say there is another string where a occurs 1 times and b occurs 21 times and then also string becomes 121. So the delimiter (here #) is needed to separate the count for each character in string format.


  • 0
    R

  • 0
    T
    This post is deleted!

  • 0
    T

    Another way to generate a hash code is using primes.

    Hard-code 26 primes in an array
    Generate a hash for by multiplying the corresponding primes for every character of a string.

    This hash will be unique for every anagram class. Of course, you want to be very careful about not running into an overflow.


  • 0

    @tarxvzf said in Group Anagrams:

    be very careful about not running into an overflow

    How?


  • 0
    F

    For Approach #1, why the space complexity is O(N∗K)? Thanks.


  • 0
    S

    I am trying to submit following code which is in C# but it somehow fails to compile. This works fine when I run this on my visual studio. Am I missing something ?

    public class Solution {

    public Dictionary <string, IList> GroupAnagrams(string[] strs) 
    {
        Dictionary <string, IList> map = new Dictionary <string, IList>();
        
        foreach (string str in strs)
        {
            char[] ch = str.ToCharArray();
            Array.Sort(ch);
            string key = new string (ch);
            
            if (!map.ContainsKey(key))
            {
                map.Add (key, new ArrayList());
            }
            
            map[key].Add(str);
        }
        return  map;
    }
    

    }

    // ERROR
    Cannot implicitly convert type 'System.Collections.Generic.Dictionary<string, System.Collections.IList>' to 'System.Collections.Generic.IList<System.Collections.Generic.IList<string>>'. An explicit conversion exists (are you missing a cast?)


Log in to reply
 

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